LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Confusion with extremely basic monte carlo pi program

Solved!
Go to solution

Hello all,

I am having the most peculiar behavior with an extremely simple VI that I do not understand.

I am writing a program to approximate Pi by randomly generating points within X: [0,1) Y:[0,1), calculating the ratio of points inside an inscribed circle and outside of it in a square. I understand the math and the theory perfectly fine.

 

What I don't understand.....:

superBasic.png

This is my program. If i set "# of points" to 1 - ~40000, the program works fine and a relatively decent approximation of pi comes out (e.g. 3.1522). However, if I exceed ~40000 points, my program suddenly gives a clearly incorrect result, sometimes being ~0.5, sometimes being negative (which shouldn't be possible). I would like to know, why is this occurring and can it be rectified?

 

0 Kudos
Message 1 of 4
(2,888 Views)
Solution
Accepted by Gryffin

The function "Boolean To (0,1)" is outputting an I16.  When the sum exceeds 32367, it wraps around.

Convert the output of "Boolean To (0,1)" to I32 inside the loop.

"If you weren't supposed to push it, it wouldn't be a button."
Message 2 of 4
(2,865 Views)

Wow what a simple reason.

Thank you very much!

0 Kudos
Message 3 of 4
(2,855 Views)

Taking this a bit further, here are some tips for the future:

 

  • Instead of squaring, summing and rooting, you can use complex math primitives instead.
  • It is inefficient to build a potentially huge array at the autoindexing output tunnel just to reduce it to a scalar a nanosecond later by summing all elements. It takes N times less memory to just accumulate the running sum in an initialized scalar shift register!
  • Since you can initialize the shift register with a suitable datatype that can hold all possible numbers, you don't need to worry about the output of "boolean to (0,1)".

Here is a quick example:

 

PiApprox.png

 

(note that "re/im to complex" followed by "absolute value" would be more efficient because you don't care about the theta output. See also our NI week presentation form 2016.)

Message 4 of 4
(2,843 Views)