简体   繁体   English

C / C ++中sqrt函数的保证精度

[英]Guaranteed precision of sqrt function in C/C++

Everyone knows sqrt function from math.h / cmath in C/C++ - it returns square root of its argument. 每个人都知道C / C ++中math.h / cmath sqrt函数 - 它返回其参数的平方根。 Of course, it has to do it with some error, because not every number can be stored precisely. 当然,它必须有一些错误,因为不是每个数字都可以精确存储。 But am I guaranteed that the result has some precision? 但我保证结果有一定的精确度吗? For example, 'it's the best approximation of square root that can be represented in the floating point type used or if you calculate square of the result, it will be as close to initial argument as possible using the floating point type given`? 例如,'它是可以用浮点类型表示的平方根的最佳近似值, or如果计算结果的平方,它将使用给定的浮点类型尽可能接近初始参数?

Does C/C++ standard have something about it? C / C ++标准有什么关于它的吗?

For C99, there are no specific requirements. 对于C99,没有具体要求。 But most implementations try to support Annex F: IEC 60559 floating-point arithmetic as good as possible. 但是大多数实现试图尽可能地支持附件F:IEC 60559浮点运算 It says: 它说:

An implementation that defines __STDC_IEC_559__ shall conform to the specifications in this annex. __STDC_IEC_559__应符合本附件中的规范。

And: 和:

The sqrt functions in <math.h> provide the IEC 60559 square root operation. <math.h>sqrt函数提供IEC 60559平方根操作。

IEC 60559 (equivalent to IEEE 754) says about basic operations like sqrt : IEC 60559(相当于IEEE 754)讲述了像sqrt这样的基本操作:

Except for binary <-> decimal conversion, each of the operations shall be performed as if it first produced an intermediate result correct to infinite precision and with unbounded range, and then coerced this intermediate result to fit in the destination's format. 除了二进制< - >十进制转换之外,每个操作都应该执行,就好像它首先产生一个正确到无限精度和无限范围的中间结果,然后强制这个中间结果以适应目标的格式。

The final step consists of rounding according to several rounding modes but the result must always be the closest representable value in the target precision. 最后一步包括根据几种舍入模式进行舍入,但结果必须始终是目标精度中最接近的可表示值。

This question was already answered here as Chris Dodd noticed in the comments section. Chris Dodd在评论部分注意到,这个问题已经在这里得到了解答。 In short: it's not guaranteed by C++ standard, but IEEE-754 standard guarantees me that the result will be as close to the 'real result' as possible, ie error will be less than or equal to 1/2 unit-in-the-last-place. 简而言之:C ++标准无法保证,但IEEE-754标准保证了结果尽可能接近“实际结果”,即误差将小于或等于1/2单位。 -last的地方。 In particular, if the result can be precisely stored, it should be. 特别是,如果可以精确地存储结果,那么它应该是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM