Note that there are some explanatory texts on larger screens.

plurals
  1. POnot random enough for monte carlo
    primarykey
    data
    text
    <p>I am trying to generate values from a normal distribution using a monte carlo method, as per the website <a href="http://math60082.blogspot.ca/2013/03/c-coding-random-numbers-and-monte-carlo.html" rel="nofollow">http://math60082.blogspot.ca/2013/03/c-coding-random-numbers-and-monte-carlo.html</a></p> <p>I modified the code a bit from the original so it calculates the variance and mean for the numbers generated directly to check if the method is working rather than do the tests separately (same difference really but just a heads up).</p> <p><strong>Question</strong></p> <p>Regardless of what I do, the variance is way above 1 and the mean is not zero. Is it possible the pseudo-random numbers generated aren't random enough?</p> <p><strong>Code</strong></p> <p><strong>PLEASE NOTE THAT THE AUTHOR OF THE ABOVE GIVEN WEBSITE IS THE PERSON WHO WROTE THE CODE</strong></p> <pre><code>#include &lt;cstdlib&gt; #include &lt;cmath&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; using namespace std; // return a uniformly distributed random number double uniformRandom() { return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. ); } // return a normally distributed random number double normalRandom() { double u1=uniformRandom(); double u2=uniformRandom(); return cos(8.*atan(1.)*u2)*sqrt(-2.*log(u1)); } int main() { double z; int N=1000; double array[N]; double mean=0 ,variance=0; srand(time(NULL)); for(int i=0;i&lt;N;i++) { z=normalRandom(); cout &lt;&lt; i &lt;&lt; "-&gt;"&lt;&lt; z&lt;&lt; endl; mean+=z; array[i]=z; } mean=mean/N ; cout &lt;&lt; " mean = " &lt;&lt; mean &lt;&lt; endl; for(int i=0;i&lt;N;i++) { variance = variance + (mean - array[i])*(mean - array[i]); } variance = variance/N; cout &lt;&lt; " variance = " &lt;&lt; variance &lt;&lt; endl; return 0; } </code></pre> <p><strong>UPDATE</strong></p> <p>Apparently as pointed by users, I screwed up and the program was not working because of a very silly mistake.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload