pi in python

1  # !/usr/bin/env python                                                                            
2  # -*- coding:utf-8 -*- 
3  # ######################### ## 
4  # File Name: pi.py 
5  # Author: frank 
6  # Mail: [email protected] 
7  # Created Time: 2018-04-29 15:46:50 
8  # ######### ################## 
9  
10  import random
 11  import time
 12  
13  # spigot algorithms Calculate pi 
14  #Approximate formula calculation of pi
15  # pi = 0.0 
16  # N = 1000 
17  #
 18  # for k in range(N): 
19  #     pi += 1/pow(16, k) * (4/(8*k+1) - 2/( 8*k+4) - 1/(8*k+5) - 1/(8*k+6)) 
20  #
 21  # print(pi); 
22  
23  # Monte Carlo method to calculate pi 
24  # Thought: use Probabilistic method to get the area S of the circle, and then divide the area of ​​the circle by the square of the radius to get the value of PI, that is, PI=S/(R*R) 
25  #Set , the length of the square is a, and the radius of the inscribed circle is r, divide the square into 4 equal parts, and the coordinate origin is at the center of the circle; 
26  #Take the quarter square/inscribed circle of the first quadrant as the object, set the total number of throws as N, and the number of throws in the circle as m (m<=N) 
27  # PI = 4 * (m/N) 
28  
29  #Set r=1 in the program 
30 #The condition for the throwing point to be in the circle is: if the distance from the point (x,y) to the center of the circle is less than or equal to r, it is considered to be thrown in the circle; that is, the square root of (x*x+y*y) <= 1 
31  
32 pi = 0.0
 33  billion 599.390809S 34 # 1,000 million million 0.6s 35 # 10,000 million 6.05s 36 # 100,000 million1 million 59.98s 37 n = 1000000000
 38 r = 1.0
 39 m = 0
 40 41 42 Time_Start = Time.Perf_counter ()
 43 for i in range(N):
 44      x = random.random()
 45      y = random.random()

 
 
 
 
 
 46      if (pow((x**2 + y**2), 0.5) <= r):
 47      ¦ m += 1 ;
 48  
49 pi = 4*m/ N
 50  print ( "The pi is: {:f },m={:d} " .format(pi,m))
 51  print ( " Calculation time: {:f}s " .format(time.perf_counter()-time_start))

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325126429&siteId=291194637