Monte Carlo algorithm the main idea of calculating the circumference rate is to plot the incircle of a square with a fixed edge length of R, then, place random knots in the square and set the point to P in the circle. Then, based on the principle of attention:
P = circular area/square area = pI * r/2R * 2R = PI/4.
Pi = 4 p. In this way, when there are enough random hitting points, the probability is very close to 1/4 of pi.
# Include <iostream> <br/> # include <cstdlib> <br/> # include <ctime> <br/> using namespace STD; </P> <p> int main () <br/> {<br/> const int max_times = 200000000; <br/> srand (static_cast <unsigned int> (time (0); </P> <p> int inside = 0; <br/> for (INT I = 0; I <max_times; ++ I) {<br/> double X = static_cast <double> (RAND ()/rand_max; <br/> Double Y = static_cast <double> (RAND ()/rand_max; <br/> If (x * x + y * Y <= 1.0) + + inside; <br/> if (I % (max_times/100) = 0) cout <'. '; <br/>}</P> <p> double Pi = 4.0 * Inside/max_times; <br/> cout <"/NPI =" <pI <Endl; <br/> return 0; <br/>}
Finally, intuition tells me that if we use a pseudo-random number generator with a larger value range (RAND in the standard library can only generate a pseudo-random number with a maximum value of more than 30 thousand), the result should be better.