【基础入门题】2021.12.02
根据 Pi²/8 = 1 + 1/3² + 1/5² + 1/7² + ...,编制计算Pi近似值的函数。
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
————————————————
方法一:
def Pi(n): res = 0 for i in range(1,n+1): res += 1/(2*i-1)**2 return (res*8)**0.5 print(Pi(1000)) print(Pi(10000)) print(Pi(100000)) print(Pi(1000000)) print(Pi(10000000)) ''' 3.14127432760274 3.1415608224399487 3.141589470489344 3.1415923352799697 3.1415926217577352 '''
方法二:推导式
Pi = lambda n:(8*sum(1/(2*i-1)**2 for i in range(1,n+1)))**0.5 print(Pi(1000)) print(Pi(10000)) print(Pi(100000)) print(Pi(1000000)) print(Pi(10000000)) ''' 3.14127432760274 3.1415608224399487 3.141589470489344 3.1415923352799697 3.1415926217577352 '''
1000万次循环可以计算到7位有效数字。