Python_example 6
program_1 calculate the area of a circle
- method_1_principle
- method_2_principle
conclusion :
1.math method compare to computer mind
2.use func perf_counter to analyze the code’s time-performance simply
- method_1_code
#Prog_2 code of method 1
pi1=0
cycletime=eval(input("please input your cycle times:"))
start1=perf_counter()
for i in range(cycletime+1):
pi1 += 1/pow(16,i)*( 4/(8*i+1)- 2/(8*i+4) -\
1/(8*i+5) - 1/(8*i+6))
print("pi(1) is :{0} \nthe running time with method 1 is :{1:.5f}s".format(pi1,perf_counter()-start1))
- method_2_code
##Program_1 calculate the area of a circle
# signal "\" in python means change the line
#method2
from random import random
from time import perf_counter
darts=1000*1000
hits=0.0#why?
start=perf_counter()
for i in range(1,darts+1):
x,y=random(),random()
distance=pow(x**2+y**2,0.5)
if distance <=1.0:
#hits=hits+1
hits+=1
pi=(hits/darts)*4
print("pi(2) is :{}".format(pi))
print("the running time with method 2 is :{:.5f}s".format(perf_counter()-start))
running result
pi(2) is :3.139604 the running time with method 2 is >:3.03336s please input your cycle times:1000 pi(1) is :3.141592653589793 the running time with method 1 is >:0.01043s