Guaranteed accuracy of sqrt function in C / C ++

Everyone knows that the sqrt function from math.h / cmath in C / C ++ - returns the square root of its argument. Of course, he must do this with some error, because not every number can be stored accurately. But I'm sure the result has a certain accuracy? For example, "is this the best approximation of the square root that can be represented in a floating-point type, used by or , if you calculate the square of the result, will it be as close as possible to the original argument using the floating-point type given by?

Is there anything about this in the C / C ++ standard?

+3
c precision floating-accuracy sqrt
source share
2 answers

There are no special requirements for the C99. But most implementations try to support the maximum possible arithmetic of application F: IEC 60559. It says:

The implementation defining __STDC_IEC_559__ must conform to the specifications in this appendix.

and

The sqrt functions in <math.h> provide the square root operation of IEC 60559.

IEC 60559 (equivalent to IEEE 754) talks about basic operations such as sqrt :

With the exception of the binary and decimal conversions, each of the operations should be performed as if it first produced an intermediate result, correct for infinite precision and with unlimited range, and then forcibly brought this intermediate result into line with the target format.

The final step consists of rounding according to several rounding modes, but the result should always be the closest representable value in target accuracy.

+7
source share

This question has already been answered here , as Chris Dodd noted in the comments section. In short: it is not guaranteed by the C ++ standard, but the IEEE-754 standard guarantees me that the result will be as close as possible to the "real result", i.e. The error will be less than or equal to 1/2 units in inches - the last place. In particular, if the result can be accurately saved, it should be.

0
source share

All Articles