[SOLVED] double precision in for-loops
-
Hey there
I have a short question about doubles in for-loops.
@
for(double i=0.0; i<=2.0; i+=0.1)
@In the above example it ignores the last step 2.0, so what I get is i until 1.9. If I'm doing this
@
for(double i=0.0; i<=2.0000001; i+=0.1)
@The last step 2.0 is also executed. Does somebody know a better solution to this problem instead of my hack there?
-
You could use qFuzzyCompare instead of the =, but that would mean rewriting your loop to:
@
for(double d=0.0; d<2.0 || qFuzzyCompare(d, 2.0); d+=0.1)
@Or, you get rid of using floating points in your loop completely, and do:
@
for(int i=0; i<=20; i+=1) {
double d = double(i) / 10.0; //use d for whatever you wanted done
@The root problem is that because floating points are never precise, comparisons with floating points are not precise either.
-
Hmm, even qFuzzyCompare does not work. Well there is only the int conversion way. Thx anyway!
Edit: My fault, qFuzzyCompare works, but as you said, comparing doubles can't be the way.