C ++ sqrt函数精度为全平方 [英] C++ sqrt function precision for full squares

查看:155
本文介绍了C ++ sqrt函数精度为全平方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

x是一个整数,y = x * x.

那么可以保证sqrt(y) == x吗?

例如,我可以确定sqrt(25)sqrt(25.0)将返回5.0,而不是5.00000000034.999999998吗?

For example, can I be sure that sqrt(25) or sqrt(25.0) will return 5.0, not 5.0000000003 or 4.999999998 ?

推荐答案

不,您不能保证.对于适合浮点类型尾数动态范围的整数及其平方(典型的C/C ++ double为2 ^ 53),您可能会满意,但不一定可以保证.

No, you cannot be guaranteed. For integers and their squares that fit in the dynamic range of the floating point type's mantissa (2^53 for a typical C/C++ double), you're likely to be OK, but not necessarily guaranteed.

应避免在浮点值和精确值之间进行等值比较,尤其是精确整数值.浮点舍入模式和其他类似的东西确实会给您带来麻烦.

You should avoid equals comparisons between floating point values and exact values, especially exact integer values. Floating point rounding modes and other such things can really get in your way.

您要么想使用比较范围"来接受近似相等"的结果,要么要用整数重铸算法.有多个StackOverflow问题涉及浮点相等比较.我建议您搜索并阅读.

You either want to use a "comparison range" to accept an "approximately equal" result, or recast your algorithm in terms of integers. There are multiple StackOverflow questions covering floating point equality comparisons. I suggest you search for them and read up.

对于某类问题,我在这里写了一个替代解决方案: 找到所有数字的第n个根在一定时间间隔内

For a certain class of problem, I wrote up an alternate solution here: Find n-th root of all numbers within an interval

与依赖棘手的浮点算法相比,该解决方案采用了不同的方法.

That solution took a different approach than relying on tricky floating point arithmetic.

这篇关于C ++ sqrt函数精度为全平方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆