首页 > 解决方案 > 准确的 sqrt(1 + (x/2)^2) + x/2

问题描述

我需要进行sqrt(1 + (x/2)^2) + x/2数值计算,对于正数x。对于非常大的 值,直接使用此表达式会失败x。如何重写它以获得更准确的评估?

标签: floating-pointlanguage-agnosticnumericnumerical-computing

解决方案


对于非常大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

推荐阅读