Tarek
Tarek

Reputation: 1090

Avoiding erratic tiny numbers when working with floating point numbers

It some times happen when I use floating point numbers in c++ and only use numbers as multiples of, say 0.1, as an increment in a for loop, the actual number which is the loop iterators is not exactly multiples of 0.1 but has unpredictably other added or subtracted tiny numbers of the order of 1^-17. How can I avoid that?

Upvotes: 0

Views: 268

Answers (3)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727077

Here is an excellent article on the subject of working with floats. There is a discussion covering precisely your example - an increment of 0.1:

for (double r=0.0; r!=1.0; r+=0.1) printf("*");

How many stars is it going to print? Ten? Run it and be surprised. The code just keeps on printing the stars until we break it.

Where's the problem? As we already know, doubles are not infinitely precise. The problem we encountered here is the following: In binary, the representation of 0.1 is not finite (as it is in base 10). Decimal 0.1 is equivalent to binary 0.0(0011), where the part in the parentheses is repeated forever. When 0.1 is stored in a double variable, it gets rounded to the closest representable value. Thus if we add it 10 times the result is not exactly equal to one.

I highly recommend reading the whole article if you work a lot with floating point numbers.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308530

Use integers for the iteration and multiply by the floating-point increment before using.

Alternatively find a decimal math package and use it instead of floating point.

Upvotes: 7

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

Don't iterate over floating-point numbers.

The problem is that 0.1 can't be exactly represented in floating-point. So instead, you should do something like:

for (int i = 0; i < N; i++)
{
    float f = i * 0.1f;

    ...
}

Upvotes: 6

Related Questions