数值实验作业(第一章)

数值实验作业(第一章)

《数值计算方法》丁丽娟

P14. 2

利用级数
π 4 = 1 − 1 3 + 1 5 − 1 7 + ⋯ \frac{\pi}{4}=1-\frac{1}{3}+\frac{1}{5}-\frac{1}{7}+\cdots 4π=131+5171+
计算无理数 π \pi π的近似值。由于交错级数的部分和数列 S N S_N SN在级数的和上下摆动,截断误差将小于第一个被舍弃的项 ∣ a n + 1 ∣ \left|a_{n+1}\right| an+1. 试分析:若要使截断误差小于 1 0 − 4 10^{-4} 104 1 0 − 8 10^{-8} 108,应该取多少项求和?并分别计算 π \pi π的近似值。

实验内容、步骤及结果

由于截断误差将小于第一个被舍弃的项 ∣ a n + 1 ∣ \left|a_{n+1}\right| an+1,易编程实现:

def is_term_less_than(n, threshold):
    term = (-1) ** n / (2 * n + 1)
    return abs(term) < threshold


def calculate_series(n):
    series_sum = .0
    for i in range(n):
        term = (-1) ** i / (2 * i + 1)
        series_sum += term
    return series_sum


def main():
    expected_trunc_errs = [1e-4, 1e-5, 1e-6, 1e-8]
    for trunc_err in expected_trunc_errs:
        print(f'期望截断误差为{trunc_err}')
        n = 0
        while not is_term_less_than(n, trunc_err):
            n += 1
        print(f'需要计算{n}项')
        print(f'π的近似值为{4 * calculate_series(n)}')


if __name__ == '__main__':
    main()

实验结果分析

期望截断误差为0.0001
需要计算5000项
π的近似值为3.141392653591791
期望截断误差为1e-05
需要计算50000项
π的近似值为3.1415726535897814
期望截断误差为1e-06
需要计算500000项
π的近似值为3.141590653589692
期望截断误差为1e-08
需要计算50000000项
π的近似值为3.1415926335902506

随截断误差减小, π \pi π的估计值越精确,但计算项数也随之增大。

P14. 3

在同一坐标系下,利用plot函数画出函数
y = sin ⁡ x , y n = ∑ i = 0 n ( − 1 ) i x 2 i + 1 ( 2 i + 1 ) ! , ( n = 2 , 5 , 10 ) y=\sin x, y_n=\sum_{i=0}^n(-1)^i \frac{x^{2 i+1}}{(2 i+1)!}, \quad(n=2,5,10) y=sinx,yn=i=0n(1)i(2i+1)!x2i+1,(n=2,5,10)
的图形,并加标注说明各条曲线的含义。

实验内容、步骤及结果

import math
import numpy as np
import matplotlib.pyplot as plt
from decimal import Decimal, getcontext

getcontext().prec = 50

x = np.linspace(-2 * np.pi, 2 * np.pi, 80)

y = np.sin(x)


def taylor_series(x, n):
    result = np.zeros_like(x, dtype=np.float64)
    for i in range(n + 1):
        result += ((-1) ** i) * (x ** (2 * i + 1)) / float(Decimal(math.factorial(2 * i + 1)))
    return result


y_2 = taylor_series(x, 1)
y_5 = taylor_series(x, 5)
y_10 = taylor_series(x, 10)

plt.plot(x, y, label='y=sin(x)', color='blue')
plt.plot(x, y_2, label='y_2', color='green')
plt.plot(x, y_5, label='y_5', color='red', linestyle='--')
plt.plot(x, y_10, label='y_10', color='orange', linestyle='-.')

plt.ylim(-1.5, 1.5)

ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.legend()

plt.show()

实验结果分析

pic1

x → 0 x\to 0 x0时,用泰勒展开近似 sin ⁡ x \sin x sinx的截断误差较小。随着 x x x增大,截断误差越明显。


P13. 4, 7, 9, 10, 12

P13.4,7,9

⚠️ 10题算错了,求根公式x= (-b ± 根号Δ )/2a,分母有个2,这里是按分母是1算。感谢@十五csw指正!

P13.10,12

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值