Logarithmic division in C++ error?

Revision en1, by mcchip, 2020-07-05 19:25:19

I was dividing using the log function in C++ today when I came across an error that I couldn't find an answer for online.

Given an integer n, I wanted to find the floor of log n base 10.

It worked for most numbers besides for some powers of 10. I decided to test increasing powers of 10 from 10^1 to 10^6. I first casted the double results as integers but 10^3 and 10^6 did not give the proper output. Using the floor function on the doubles also gave the same results. I then printed the double results which corrected it, but this won't work for non-perfect powers of 10. I'm a bit confused because I heard that division and multiplication are floating-point error safe.

My code:

int a[6]={10,100,1000,10000,100000,1000000};
    for (int i=0;i<6;i++){
        int x=(int)(log(a[i])/log(10));
        double y=log(a[i])/log(10);
        cout << x << " " << y << endl;
    }

Output:

1 1 2 2 2 3 4 4 5 5 5 6

Does anyone know why this happens and how I can prevent it?

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en4 English mcchip 2020-07-05 19:28:07 7 Tiny change: '" << y << endl;\n }\n' -> '" << y << " ";\n }\n'
en3 English mcchip 2020-07-05 19:26:57 2 Tiny change: 'nOutput:\n\n1 1\n2 2' -> 'nOutput:\n1 1\n2 2'
en2 English mcchip 2020-07-05 19:25:55 0 Tiny change: '4 4\n5 5\n5 6\n\nDoes a' -> '4 4\n5 5\n\nDoes a'
en1 English mcchip 2020-07-05 19:25:19 1047 Initial revision (published)