python - Python:增加浮点精度会产生不正确的结果?
问题描述
我正在尝试编写一个函数,它递归地计算函数在给定点的 n 阶导数x
。我使用了导数的简单定义:
f'(x) = f(x + h) - f(x)
---------------
h
lim h -> 0
def deriv(f, x, n=1, h=1e-4):
if n == 0: # 0th order deriv is the function itself (base case)
return f(x)
return (deriv(f, x+h, n-1, h) - deriv(f, x, n-1, h))/h
f = lambda x: x**3
print("x\tf(x)\tf'(x)\tf''(x)\tf'''(x)")
for x in range(5, 10):
print(x, f(x), deriv(f, x), deriv(f, x, 2), deriv(f, x, 3), sep='\t')
对于h = 1e-4
,我得到以下结果:
x f(x) f'(x) f''(x) f'''(x)
5 125 75.00150000979033 30.00060075919464 5.982769835100044
6 216 108.00180000984483 36.00059699238045 6.053824108676054
7 343 147.00210000967218 42.00060175207909 5.968558980384842
8 512 192.0024000094145 48.00060651177773 5.7980287238024175
9 729 243.00270000935598 54.0005999027926 6.02540239924565
我专注于最后一列:x^3
应该是的三阶导数6
和值非常接近6
!现在我虽然h
缩小会导致更准确的结果,所以我将其更改为1e-5
,但结果不正确:
x f(x) f'(x) f''(x) f'''(x)
5 125 75.00014999664018 30.000251172168642 -28.421709430404004
6 216 108.00017999486043 36.000358250021236 -56.84341886080801
7 343 147.0002099949852 41.99989689368522 56.84341886080801
8 512 192.0002399970144 47.9997197544435 0.0
9 729 243.00026999526378 53.998974181013175 227.37367544323203
前两列似乎没问题。我认为问题在于浮点不准确,但我无法准确确定出了什么问题以及超出的阈值,结果将不准确。
解决方案
推荐阅读
- batch-file - 如何批量重命名文件为文件夹名称+递增的数字?我收到重复名称错误
- python - Spark - 如何将窗口中的行与步幅值连接起来
- c++ - 如何将函数指针从 std::function 传递给 Linux 克隆?
- flutter - 如果原始在 Flutter 中的设备上溢出,我如何有条件地渲染不同的小部件?
- c++ - 找不到 sdl2.dll
- java - 在 OneToMany 单向 Realtion 之后从数据库中检索数据
- reactjs - Visual Studio Code 不显示 IntelliSense?
- kubernetes - 请输入用户名 - ServiceAccount 部署
- angular - this.router.navigate 返回 false
- linux - 无法按我的预期设置 linux 环境变量