Calculate Pi values using the random throw dart method (randomness throwing Dart Pi Python)

Source: Internet
Author: User

Draw a square with a side length of R and a circle with a radius of R of One-fourth (as shown), throw darts at random, and calculate the π value by calculating the proportion of darts falling in the star area and the whole area.

The formula is deduced as follows:

Assuming that the square's side length R is 1, then the Dart falls on any point in the Star area (x, y), and its coordinates are bound to be less than 1 of the sum of squares (x2+y2).

The code is as follows:

ImportRandomdefFind_pi (num_of_times):#Num_of_times is the number of darts thrownnum1,num2=0,0#NUM1 the number of times the dart is thrown in the star area, num2 the number of times the dart is thrown in the dot area     forIinchRange (Num_of_times):#after each dart, the point coordinates (x, y) of the dart fall are the floating-point numbers between the 0~1x=random.random () y=random.random ()if(x**2+y**2) <1:num1+=1#if the value of the sum of its point coordinates is less than 1, then the Dart falls within the arc area, NUM1 is added once, and conversely, num2 is added once        Else: num2+=1Pi= (num1/(num1+num2)))  returnPi

Throw 1 million darts and try it:

Print (Find_pi (1000000))

Several operating results have not been the same as the actual pi value:

3.14326

3.140684

3.141544

Reference: MIT Open Class: Introduction to Computer science and programming (20th lesson)

Calculate Pi values using the random throw dart method (randomness throwing Dart Pi Python)

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.