首页 > 解决方案 > 如何避免 Python 3.7 中 f(x) = (1-cos(x))/x**2 中的小数的灾难性取消?

问题描述

如何避免 Python 3.7 中 f(x) = (1-cos(x))/x**2 中的小数的灾难性取消?

这是我到目前为止所尝试的(我知道,关键是一些三角恒等式,它可以让你避免取消,而且我也知道,使用 L'Hopital 的规则,f(x) 的极限→0 是 0.5 ,因此正确的程序输出非常接近 0.5,例如,如果您使用 x = 1.2e-4,您会得到这样的结果,但是您会用较小的数字(如 1.2e-8)取消,我需要做到这一点所以这不会发生)。

from math import *
def f(x):     #these are all the same function using different identities  
   a = (1-(sin(x)/tan(x)))/(x**2)
   b = (1-(sin(2*x)/(2*sin(x))))/(x**2)
   c = (1-((1-((tan(x/2))**2))/(1+(tan(x/2))**2)))/(x**2)
   d = (sin(x)**2+cos(x)**2-cos(x))/(x**2)
   e = (sin(x)**2+cos(x)**2-(sin(2*x)/(2*sin(x))))/(x**2)
   return a, b, c, d, e

print(k(1.2e-8))
#Output: (0.0, 0.7709882115452477, 0.0, 0.0, 0.0) - whereas need 0.5000...

标签: pythonpython-3.xfunctiontrigonometryfloating-accuracy

解决方案


像这样:

sin(x)/x * tan(x/2)/x

它一直工作到最后,x = 1e-308仍然可以。

不幸的是,我无法提供太多关于为什么它运作良好的见解。


推荐阅读