-
0 float
Hi there,
i've been doing some coding and i came across a difficulty
that (V?)C++ seems to turn a defined float 0 into very small
float numbers (order 10e-8, 10e-7) later on. I spoke
to someone who said that it is an inherent problem in VC++.
so i guess when i want to test a float variable x < 0 i should
be testing it against a very small float x < 10e-8 instead.
but how do i know that x i defined 0 will not become for
example of the order 10e-6 so it will return FALSE when i
test it against x < 10e-8???
thanx for your contributions...
:confused:
-
The precision for floating point type variables in C/C++ is :
float : 7 digits
double : 15 digits
long double : 18 digits
The reason for this is that with a finite amount of bits, it is impossible to represent every floating point value.
Code:
float epsilon = 1e-7;
float a = 123.4567890123456789;
float b = 123.4567890123456789;
if (fabs(b-a) < epsilon)
cout << "equal";
else
cout << "definately not equal";
-
This is not, perhaps, exactly on line with your specific question, but it does go to 'floats' and their representation.
When a 'float' can be represented exactly by the computer, it's referred to as a model number.
For example, let's say that our computer will hold the value 0.4512 as an exact, real value (assuming four-digit precision). The value 0.45119999, (a real number), is represented by the "model".
In effect, the computer holds 0.45119999 as 0.4512. This is a representational error referred to as the "rounding error".
(Oh, it gets better! :))
There are two ways of measuring this type of error. They are absolute error and relative error.
"Absolute error" is the difference between the model and the real number. Pretty straightforward.
"Relative error" is the absolute error divided by the real number, often represented as a percentage.
Before I put you to sleep completely, - it's been known to happen - recognize that MSVC++ may well be representing zero as a "representation" of the model versus the model itself.
Why this should take place is beyond me, but "equivalence" does seem to play a part here.
-Skipper
-
it's not c++ only. it has to do with the way floats are stored. try casting to an int, or measuring against a very low number. (i think c++ defines one called ESP somewhere...?)
-
-
-
this has all been really helpfull!!!!!!!!!!!
thanks