python之圆周率

 1 #!/usr/bin/env python                                                                           
 2 #-*- coding:utf-8 -*-
 3 ############################
 4 #File Name: pi.py
 5 #Author: frank
 6 #Mail: frank0903@aliyun.com
 7 #Created Time:2018-04-29 15:46:50
 8 ############################
 9 
10 import random
11 import time
12 
13 #spigot algorithms 计算圆周率
14 #圆周率近似公式计算
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 #蒙特卡罗方法计算圆周率
24 #思想:用概率的方法得到圆的面积S,然后用圆的面积除以半径的平方得到PI的值,即PI=S/(R*R)
25 #设,正方形的长为a,内切圆的半径为r,将正方形分为4等分,坐标原点在圆心; 
26 #以第一象限的4分之一正方形/内切圆为对象,设投掷的总次数为N,投掷在圆内的次数为m(m<=N)
27 #PI = 4 * (m/N)
28 
29 #程序中设定r=1
30 #投掷点在圆内的条件是: 点(x,y)到圆心的距离小于等于r,则认为投掷在圆内;即,(x*x+y*y)的平方根 <= 1
31 
32 pi = 0.0
33 #1,000,000,000 十亿 599.390809s
34 #1,000,000 百万 0.6s
35 #10,000,000 千万  6.05s
36 #100,000,000 一亿  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("圆周率是:{:f},m={:d}".format(pi,m))
51 print("计算耗时:{:f}s".format(time.perf_counter()-time_start))

 

posted @ 2018-04-29 21:09  suonikeyinsu  Views(1083)  Comments(0Edit  收藏  举报