Reputation: 325
I have a very weird error with c++. I have two values, max and singleStep. The number of steps is stepsInt and/or stepsDbl:
max = 100;
singleStep = 0.1;
// This means that I have 100/0.1 = 1000 numbers betwwen 0 and 100
double stepsDbl = max/singleStep;
int stepsInt = (int)(stepsDbl);
cout << stepsDbl << stepsInt;
You can expect an output like this:
1000 1000
However I'm getting this output:
1000 999
What is more, if I try a different value for singleStep, for instance 0.2, I get again wrong values
500 499
I don't know what is happening but is pretty weird... If anyone has a solution for this problem I would appreciate that solution.
Thanks
Upvotes: 0
Views: 126
Reputation: 67380
Try this instead:
int stepsInt = (int)floor(stepsDbl+.5);
The "problem" you're seeing is because of the way floating point numbers are stored internally.
Upvotes: 0
Reputation: 477010
Floating point numbers on your platform cannot exactly represent numbers which do not have a finite binary expansion, so you will naturally have uncertainty when using those numbers. Use rationals instead and keep "0.1" as "1/10" when possible.
("Finite binary expansion" means "finite sum of powers of two". 1/5 is not a finite sum of powers of 2, and neither is 1/3 nor 1/10.)
Upvotes: 0
Reputation: 61369
(int)
casts round toward zero, and (double)
arithmetic is inherently unreliable (look up floating point math). operator<<(double)
rounds to nearest, so a value like 999.999999999999
resulting from accumulated FP inaccuracy will print as 1000
directly and 999
when naïvely cast to (int)
.
Upvotes: 1