floating point rounding errors

I can't explain this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cmath>
#include <iostream>
using namespace std;

int main()
{
    // n
    double n = log(125)/log(5);

    // n2
    int base = 5;
    int number = 30;
    double n2  = log10((number + 1) * (base - 1) + 1) / log10(base);

    cout << (int) n <<  " --> " << (int) n2 << endl;
}


log(125)/log(5) returns three as expected.
(number + 1) * (base - 1) + 1 is 125. But If I put that as an argument into the log function and cast it into an int it gives me 2. I am seriously confused.

Thanks in advance
Last edited on
Doubles aren't much precise, so the value of n2 may be 2.99999 or something like that.
When you cast a double into an integer the decimal digits are truncated.
Floating point math is an approximation. Read sectsion 29.18:

http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.18


29.16 and 29.17 are also good reads but do not directly address this particular problem

EDIT: way too slow -- that's what I get for going to the bathroom before posting XD
Last edited on
Topic archived. No new replies allowed.