#1099 Invalid log10 value for some cases in JavaScript

Yuri Strot Mon 24 May 2010

Hi,

I have a strange problem with the following code:

@Js
class TestClass
{
  Void main()
  {
    echo(get.toFloat.log10.toInt)
    echo(1000.toFloat.log10.toInt)
  }

  Int get() { 1000 }
}

In the browser console (the same for Firefox and Chrome) I have: 2 3

However in java it works fine. Do you have any ideas?

andy Tue 25 May 2010

JavaScript does not have a native log10 method so we have to use division to approximate which appears is causing the precision issues you are seeing:

Math.log(1000) / Math.LN10  =>  2.9999999999999996  (Chrome)

Float.toInt uses Math.floor to convert to Int. So you should be seeing 2 for both the above cases (which will differ than the JVM which produces 3).

helium Tue 25 May 2010

Should there be an integer logarithm?

In the meantime you could use something like:

int iLog10(int x)
{
   if (x <= 0)
      throw ...

   i := -1
   m := 1
   while (x >= m)
   {
      m *= m
      i += 1
   }
   return i
}

Login or Signup to reply.