Monte Carlo algorithm for calculating the circumference Pi (C ++)

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.