首页 > 解决方案 > 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

前两列似乎没问题。我认为问题在于浮点不准确,但我无法准确确定出了什么问题以及超出的阈值,结果将不准确。

标签: python

解决方案


推荐阅读