I am using this crude monte-carlo integration technique to find out the value of $\pi$ and noticed that the integration value steadily deviates from the actual value as I increase the number of sample points. The code is:
using namespace std;
float f(float x)//definition of the integrand
float rand1()//random number generator between 0 and 1
float calcint(float xi,float xf,float yi,float yf,float N)//integrator
float x=(xf-xi)*rand1();float y=(yf-yi)*rand1();
for (int i=1; i<N; i=i+N/10)//lists integration value for different sampling
The problem is limited precision of
float type. It has 24 significant precision bits, and the maximal possible integer number that can be represented by
float type is 16777216 while 16777217 cannot be represented because it requires 25 significant bits (1 0000 0000 0000 0000 0000 0001 in binary). See more details here: Which is the first integer that an IEEE 754 float is incapable of representing exactly?
It means that when you add 1.0f to 16777216.0f, the result will be 16777216.0f instead of 16777217.0f. Therefore, you should use integer type for
n instead of floating point type to count the number of events.