2024.10 作业 - 教科书P109~112整理 代码部分
- P119-1
1 | #! /usr/bin/python3 |
P119-2
1
2
3
4
5
6
7
8
9
10
11#! /usr/bin/python3
# encoding=utf-8
h = 100
sumh = 0
for i in range(10):
sumh+=h
h/=2
sumh+=h
print("共经过:"+str(sumh)+"米","当前高度:"+str(h)+"米")P119-3
1 | #! /usr/bin/python3 |
- P119-4
1 | #! /usr/bin/python3 |
- P119-5
1 | #! /usr/bin/python3 |
- P120-121
1 | #! /usr/bin/python3 |
- P112-1
1 | #! /usr/bin/python3 |
- P112-2
(1) 数值积分法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import numpy as np
def f(x):
return 4 / (1 + x**2)
def trapezoidal_rule(a, b, n):
x = np.linspace(a, b, n+1)
y = f(x)
h = (b - a) / n
integral = (h / 2) * (y[0] + 2 * np.sum(y[1:n]) + y[n])
return integral
a = 0
b = 1
n = 1000000
pi_approx = trapezoidal_rule(a, b, n)
print("使用数值积分法计算的π值: "+pi_approx)(2) 泰勒级数法
1
2
3
4
5
6
7
8
9
10def calculate_pi(n_terms):
pi_approx = 0
for k in range(n_terms):
pi_approx += ((-1) ** k) / (2 * k + 1)
return 4 * pi_approx
n_terms = 1000000
pi_value = calculate_pi(n_terms)
print(f"使用泰勒级数法计算的π值: {pi_value}")(3) 韦达公式法
1
2
3
4
5
6
7
8
9
10
11
12
13
14import math
def vieta_pi(n_terms):
a = math.sqrt(2)
pi_approx = 2 / a
for _ in range(n_terms - 1):
a = math.sqrt(2 + a)
pi_approx *= 2 / a
return 2 * pi_approx
n_terms = 1000
pi_value = vieta_pi(n_terms)
print("使用韦达公式法计算的π值:"+ pi_value)(4) 拉马努金公式法
1 | from decimal import Decimal, getcontext |
- (5) 迭代法
1 | def calculate_pi(iterations): |
很显然除了韦达公式法我看不懂一点(逃
- P117-3
不是我总不能真写一个聊天机器人吧