python - 计算 1/tanh(x) - 1/x 对于非常小的 x

标签 python numpy math rounding

我需要计算数量

1/tanh(x) - 1/x

对于 x > 0,其中 x 可以非常小也可以非常大。

对于小的x,我们有渐近

1/tanh(x) - 1/x  ->  x / 3

对于大的x

1/tanh(x) - 1/x  ->  1

无论如何,在计算表达式时,已经从 10^-7 和更小的舍入误差导致表达式被计算为恰好为 0:

import numpy
import matplotlib.pyplot as plt


x = numpy.array([2**k for k in range(-30, 30)])
y = 1.0 / numpy.tanh(x) - 1.0 / x

plt.loglog(x, y)
plt.show()

enter image description here

最佳答案

对于非常小的x,可以使用the Taylor expansion of 1/tanh(x) - 1/x around 0 ,

y = x/3.0 - x**3 / 45.0 + 2.0/945.0 * x**5

误差的阶数为O(x**7),所以如果选择10^-5作为断点,则相对误差和绝对误差为远低于机器精度。

import numpy
import matplotlib.pyplot as plt


x = numpy.array([2**k for k in range(-50, 30)])

y0 = 1.0 / numpy.tanh(x) - 1.0 / x
y1 = x/3.0 - x**3 / 45.0 + 2.0/945.0 * x**5
y = numpy.where(x > 1.0e-5, y0, y1)


plt.loglog(x, y)
plt.show()

enter image description here

关于python - 计算 1/tanh(x) - 1/x 对于非常小的 x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43279071/

相关文章:

java - 使用 Chaquopy 在 Android 中自写 python 代码

python - matplotlib.pcolor 非常慢。备择方案?

.net - "Math.DivRem"和 % 运算符之间的区别?

algorithm - 线段与凸多边形的交集

python - 在 python 中正确使用 subprocess.PIPE?

python - 无法理解 PyQt 中的一行代码

python-3.x - 用不同的随机统一变量替换 Pandas DataFrame 中的 NaN 值

python - MATLAB 中对称矩阵的复特征向量

python - 查看数据帧的行,如果行上的大多数项目也是 x,则返回结果(x)

java - 二进制补码,减去两个负二进制数