python - 如何避免 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...
解决方案
像这样:
sin(x)/x * tan(x/2)/x
它一直工作到最后,x = 1e-308
仍然可以。
不幸的是,我无法提供太多关于为什么它运作良好的见解。
推荐阅读
- c# - .Net 5 发布单个文件 - 生成 exe 和 dll
- hyperledger-fabric - 如何在 Hyperledger Fabric 测试网络中配置 3rd Party CA?
- mysql - MySQL 将 ID 的 JSON_ARRAY 转换为值的 JSON_ARRAY [MySQL 8]
- c++ - 为什么 std::invoke_result_t 为可调用对象提供其他返回类型而不是特征?
- r - 通过tidyverse中的索引将较小的数据帧连接到较大的数据帧?
- audiounit - AUAudioUnit hosting
- c - C中关于内存分配的一些问题
- flutter - NoSuchMethodError:类“FlutterError”没有实例获取器“代码”。接收方:“FlutterError”实例尝试调用:代码)
- c++ - 是否可以从 C++ 中的线程返回退出代码?
- html - 位置粘性无法在 Iphone 上的 Direction RTL 中正常工作