0

I am trying to make a small graphics demo, and was increasing a variable (let's say it's called B) by 0.05 every iteration. Problem, the code does not work as expected.

#include <iostream>

int main(void)
{
    double b = 0;
    for (int i = 0; i < 3001; ++i) {
        if (b < 150)
            b += 0.05;
        std::cout << b << std::endl;
    }
}

The expected outcome is for the last results to be "150.00", or "150", but instead it prints "150.05". Somehow, the code runs the b += 0.05; one more time. I honestly do not know how to search for a fix on the internet, there's no way I can word this error in a short sentence.

CattoByte
  • 43
  • 5
  • 1
    Not all possible decimal fractions are equally representable as binary fractions. – πάντα ῥεῖ Dec 20 '20 at 14:08
  • @πάνταῥεῖ, I'm sorry, I'm not sure I understand what you mean by that. – CattoByte Dec 20 '20 at 14:08
  • 1
    https://floating-point-gui.de/ I am pretty sure we have a duplicate about this topic here at Stack Overflow as well. – πάντα ῥεῖ Dec 20 '20 at 14:10
  • Thank you, this answers my question, but is there a way that I can make it precise without making the code too complicated? @πάνταῥεῖ – CattoByte Dec 20 '20 at 14:11
  • @πάνταῥεῖ I like that guide, much better than the 'long article with lots of formulae'. – john Dec 20 '20 at 14:20
  • @CattoByte In other words: `if (b < 150)` is wrong and not reliable for a `double` or `float` datatype of `b`, you'll need to use [`std::numeric_limits::epsilon`](https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon) for comparisons. – πάντα ῥεῖ Dec 20 '20 at 14:32

2 Answers2

0

It is because of double precision. You can solve it by using integers:

int main(void)
{
    int b = 0;
    for (int i = 0; i < 3001; ++i) {
        if (b < 15000)
            b += 5;
        std::cout << b/100 << std::endl;
    }
}
Dorin Baba
  • 1,578
  • 1
  • 11
  • 23
0

It seems like the code is fine, the problem is how computers calculate it, take a look at this website. Basically not all decimal fractions can be represented in binary: Binary uses 0 and 1 Decimal uses 0,1,2,3,4,5,6,7,8 and 9

CattoByte
  • 43
  • 5