15 January 2012

Challenge: Random Number order of operation usage

Below is two examples. Each example should do the same thing but it turns out there is a difference in random number usage between the two. The second example differs from the first example in that the call to the linearSampling() function has been moved out of the circle.isInside() function argument list and replaced with the declaration of double X and double Y.

The two example codes do not give the same results on the same problem due to a difference in the order of random number usage. Can you tell why?

1:   //Example 1
2: unsigned accepted = 0;
3: for(unsigned n=0; n<nTests; ++n) {
4: if( circle.isInside( linearSampling(Range[Shape::X].data(), rng) , linearSampling(Range[Shape::Y].data(), rng) ) )
5: ++accepted;
6: }
7:
8: //Example 2
9: unsigned accepted = 0;
10: for(unsigned n=0; n<nTests; ++n) {
11: double PointX=linearSampling(Range[Shape::X].data(), rng);
12: double PointY=linearSampling(Range[Shape::Y].data(), rng);
13: if( circle.isInside( PointX , PointY ) )
14: ++accepted;
15: }
16:
17: double
18: linearSampling(double* pCoord, rng_t& rng) {
19: return pCoord[0] + ( (pCoord[1]-pCoord[0]) * rng() );
20: }
21:

No comments: