floating-point - 准确的 sqrt(1 + (x/2)^2) + x/2
问题描述
我需要进行sqrt(1 + (x/2)^2) + x/2
数值计算,对于正数x
。对于非常大的 值,直接使用此表达式会失败x
。如何重写它以获得更准确的评估?
解决方案
对于非常大x
的情况,您可以考虑x/2
:
sqrt(1 + (x/2)^2) + x/2
= (x/2) * sqrt( 1/(x/2)^2 + (x/2)^2/(x/2)^2) + x/2
= (x/2) * sqrt( (2/x)^2 + 1 ) + x/2
因为x > 2/sqrt(eps)
平方根实际上将计算为 1 并且您的整个表达式将简化为 just x
。假设您需要覆盖整个范围[0, infinity]
,我建议您在该点进行分支并x
在这种情况下返回您的原始公式,否则:
if x > 2/sqrt(eps) // eps is the machine epsilon of your float type
return x
else
return sqrt(1 + (x/2)^2) + x/2
推荐阅读
- python - 如何使用python有效地查找具有一定间隔的两个地理位置/位置之间的所有坐标
- python - 如何在熊猫数据框子集操作中将 end_time 指定为当前时间
- java - 请求范围的 Spring AOP 建议被调用两次
- php - 如何使用 ACF 复选框值进行 meta_query,因为它们将自己存储为数组?
- angular - 愚蠢的 UI 组件:如何在输出发出后应用条件行为
- angularjs - 如果数组中的对象缺少字段,如何隐藏元素
- python - 排序后如何获取数据帧的索引
- sql - 我想将数字更改为小时:分钟
- ajax - 字段中的值不会通过 ajax 传递给 php
- c# - UTC 到夏令时的本地时间