About float

Hello everyone!

I have this problem:

1
2
3
float a = 2;
a = sqrt(a);
a = a * a;


after the program finished, a = 1.999999, how can I correct this value because I want to compare with other float variable?

Regards
Last edited on
The square root of 2 is not a valid float; it lies between two floats, namely
1.41421353816986083984375 and 1.414213657379150390625. It is a lot closer to 1.41421353816986083984375, and the default rounding mode is to nearest, so that's the value sqrt returns in C++ (in C, what it returns depends on what header you pull it from, but either way you end up with 1.41421353816986083984375 as you store it in your float variable)

When you multiply 1.41421353816986083984375 by itself, you get 1.99999993154291644259501, which is once again not a valid float. When you store it in a float, you end up with the closest thing, which is 1.99999988079071044921875, and that is your final value of a. Note that the next float after this one is 2.0, so you're away only by one ulp (unit in the last place)

First of all, use doubles, they are intended to be the default floating-point type. You aren't using shorts every time you want an integer, are you?

Second, rethink your math taking into account that you're not dealing with infinite precision. What' s the actual goal of the program, what is it trying to solve?

As the last resort, allow for the one or two ulps of a difference when comparing floats.

Last edited on
Topic archived. No new replies allowed.