Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy log(1000)/log(10) isn't the same as log10(1000)?
    primarykey
    data
    text
    <p>Today, I came across quite strange problem. I needed to calculate string length of a number, so I came up with this solution</p> <pre><code>// say the number is 1000 (int)(log(1000)/log(10)) + 1 </code></pre> <p>This is based on mathematical formula</p> <p><code>log</code><sub>10</sub><code>x = log</code><sub>n</sub><code>x/log</code><sub>n</sub><code>10</code> (explained <a href="http://en.wikipedia.org/wiki/Logarithm#Change_of_base" rel="nofollow noreferrer">here</a>)</p> <p>But I found out, that in C,</p> <pre><code>(int)(log(1000)/log(10)) + 1 </code></pre> <p>is <strong>NOT</strong> equal to</p> <pre><code>(int) log10(1000) + 1 </code></pre> <p>but it should be. </p> <p>I even tried the same thing in Java with this code</p> <pre><code>(int) (Math.log(1000) / Math.log(10)) + 1 (int) Math.log10(1000) + 1 </code></pre> <p>but it behave the same wrong way.</p> <p>The story continues. After executing this code</p> <pre><code>for (int i = 10; i &lt; 10000000; i *= 10) { System.out.println(((int) (Math.log10(i)) + 1) + " " + ((int) (Math.log(i) / Math.log(10)) + 1)); } </code></pre> <p>I get </p> <pre><code>2 2 3 3 4 3 // here second method produces wrong result for 1000 5 5 6 6 7 6 // here again </code></pre> <p>So the bug seems to occur on every multiple of 1000.</p> <p>I showed this to my C teacher, and he said that it might be caused by some type conversion error during log division, but he didn't know why.</p> <p>So my questions are</p> <ul> <li><strong>Why isn't <code>(int) (Math.log(1000) / Math.log(10)) + 1</code> equal to <code>(int) Math.log10(1000) + 1 </code>, while it should be, according to the math.</strong></li> <li><strong>Why is it wrong only for multiples of 1000?</strong></li> </ul> <p><strong>edit:</strong> It is not rounding error, because </p> <pre><code>Math.floor(Math.log10(i)) + 1 Math.floor(Math.log(i) / Math.log(10)) + 1 </code></pre> <p>produce same, wrong output</p> <pre><code>2 2 3 3 4 3 5 5 6 6 7 6 </code></pre> <p><strong>edit2:</strong> I have to round down, because I want to know the <strong>number of digits</strong>.</p> <pre><code>log10(999) + 1 = 3.9995654882259823 log10(1000) + 1 = 4.0 </code></pre> <p>If I just round, I get same result (4), which is wrong for 999, because it has 3 digits.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload