mcchip's blog

By mcchip, history, 4 years ago, In English

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 << " ";
    }

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?

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it