Sqrt() Precision

Hi there,

I've stumbled upon something odd when i was implementing a sqrt() function in a C program. It seems that sqrt() from math.h will not give you the right answer if you are using float values as input. Well to be exact, the answer is right up to the 8th position. Even when using sqrt() with double will differ after the 17th position.

To wrap it up: Is there a way to get the the "precise" sqrt by implementing another sqrt() function in the code in a float value.

Thanks

Background: For everyone asking why the precision is so important. The sqrt is going to be implemented in a optimization algorithm. I've found out that when using 'sqrt(a)*sqrt(a)' will give you different results than just 'a' because the gradient that is used in the algorithm behaves differently (FYI the algorithm is tested and good).
Well to be exact, the answer is right up to the 8th position.
Representing 8 decimal digits requires 27 bits. float has a 23-bit mantissa, allowing for good precision up to 6 decimal digits.

Even when using sqrt() with double will differ after the 17th position.
17 decimal digits require 57 bits. double has a 52-bit mantissa (15 decimal digits).

It seems that sqrt() from math.h will not give you the right answer if you are using float values as input.


As an aside, the sqrt from math.h does not accept float values.

http://www.cplusplus.com/reference/clibrary/cmath/sqrt/
closed account (S6k9GNh0)
I seem to be missing something here... (like the obvious contradiction between Moschops statement and his references).
obvious contradiction between Moschops statement and his references

Here's a different reference that makes it easier to understand.

http://pubs.opengroup.org/onlinepubs/007908799/xsh/math.h.html

math.h is the C standard header. cmath is the C++ standard header.

The long and the short of it (a ha ha, excuse the pun) is don't use math.h - use cmath. If you've got some mutant math.h that includes a float version of something, there's no guarantee that every math.h the code will ever be compiled with shall include a similar mutant version.

math.h from before C99 (I think) did not support anything other than double into sqrt. C99 changed the game; not helpful if you're coding in C++98. I don't have C++03 defninition to hand, so can't check what that says about math.h (C++98 simply says it's the C standard math.h, which presumably means the one active in 1998).
Last edited on
Topic archived. No new replies allowed.