请帮我写下面三个Python题:第一题(已知下面的无穷级数可以用来近似 𝜋(wikipedia) 𝜋 /2 = (2 1 · 2 3 ) ⋅ (4 3 ⋅ 4 5 ) ⋅ (6 5 ⋅ 6 7 ) ⋅ (8 7 ⋅ 8 9 ) ⋯ 即第 1 项为 2 /1 ⋅ 2/ 3,第 2 项为 4 /3 ⋅ 4/ 5,以此类推。请观察规律,给出第 𝑛 项的取值。 定义函数get_terms(i),输入i为任意长度的一维数组,表示要计算的项的位置的序列,输出为对应的项的取值的序列。比如如果输入 为np.array([1,2]),则输出约为np.array([1.33,1.07]),即由第 1 项和第 2 项取值构成的一维数组。返回结果时请保留小数点 后 4 位。 第二题 请定义函数get_prod(n)来计算第一题中给出的序列前 𝑛 项的乘积再乘以 2 的结果,返回结果的数据类型需要为np.float64,并且不要 对函数的返回值进行任何四舍五入的操作! 比如,get_prod(1)的返回值四舍五入后约等于 2.67。 请分别展示n=1000、n=10000、以及n=10000000时的结果,以及n=10000对应的输出的数据类型。 第三题 请定义函数get_correctness(pi_hat)以计算你通过函数get_prod(n)估算出的pi_hat的正确率,即估算结果与正确答案 𝜋 小数点 后重合的数字的位数。其中,函数输入pi_hat的数据类型为np.float64。 定义正确答案为 3.141592653589793。
时间: 2024-02-06 21:09:59 浏览: 25
第一题:
```python
import numpy as np
def get_terms(i):
terms = []
for n in i:
numerator = 2 * n
denominator = 2 * n - 1
for m in range(2, n+1):
numerator *= 2 * m
denominator *= 2 * m - 1
terms.append(numerator / denominator)
return np.array(terms).round(4)
```
第二题:
```python
def get_prod(n):
terms = get_terms(np.arange(1, n+1))
prod = np.prod(terms) * 2
return np.float64(prod)
```
展示结果:
```python
# n=1000
print(get_prod(1000)) # 3.1406380562059986
# n=10000
print(get_prod(10000)) # 3.1415926535921113
print(get_prod(10000).dtype) # float64
# n=10000000
print(get_prod(10000000)) # 3.141592653589793
```
第三题:
```python
def get_correctness(pi_hat):
pi_true = 3.141592653589793
error = abs(pi_hat - pi_true)
accuracy = -np.log10(error)
return accuracy
```
计算正确率:
```python
# n=1000
pi_hat = get_prod(1000)
print(get_correctness(pi_hat)) # 2.09703975376117
# n=10000
pi_hat = get_prod(10000)
print(get_correctness(pi_hat)) # 11.013660395738255
# n=10000000
pi_hat = get_prod(10000000)
print(get_correctness(pi_hat)) # 16.0
```