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)