计算:自然对数的底e和圆周率pi

时间:2022-02-04 23:26:04

有人问圆周率怎么算。纸上没法写。

纸上也就写个大概,毕竟我的大脑不是编译器。


贴代码。

# calc e using taylor series  
def my_exp(x,terms=20):  
    return sum([x**i/math.factorial(i) for i in range(terms)])  
  
print(my_exp(1)) # e = 2.718281828459 ...  
  
       
# calc pi using 2-dim uniform distribution  
N = int(1e6)  
l1 = [random.random() for _ in range(N)]  
l2 = [random.random() for _ in range(N)]  
  
pi_val = sum([x < 1 for x in [l1[i]**2 + l2[i]**2 for i in range(N)]]) / N * 4  
print(pi_val)  
  
# calc pi using fourier series  
pi_val2 = math.sqrt(sum([x**-2 for x in range(1,N)])*6)  
print(pi_val2)  

Done!