Everyone knows sqrt
function from math.h
/cmath
in C/C++ - it returns square root of its argument. 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 usedor
if you calculate square of the result, it will be as close to initial argument as possible using the floating point type given`?
Does C/C++ standard have something about it?
For C99, there are no specific requirements. But most implementations try to support Annex F: IEC 60559 floating-point arithmetic as good as possible. It says:
And:
IEC 60559 (equivalent to IEEE 754) says about basic operations like
sqrt
: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. 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, i.e. error will be less than or equal to 1/2 unit-in-the-last-place. In particular, if the result can be precisely stored, it should be.