Calculating Base-n logarithm in Ruby

Scott Allen picture Scott Allen · Jan 23, 2011 · Viewed 7.1k times · Source

This one seems like an easy one, but I'm having trouble calculating log (Base 5) in Ruby.

Clearly the standard base-10 log works fine:

>> value = Math::log(234504)
=> 12.3652279242923

But in my project I need to use Base 5. According to the ruby docs (http://www.ruby-doc.org/core/classes/Math.html#M001473) it seems I should be able to do this:

Math.log(num,base) → float

>> value = Math::log(234504, 5)
ArgumentError: wrong number of arguments (2 for 1)
    from (irb):203:in `log'
    from (irb):203
    from :0

Which it doesn't like. Anyone know how to calculate logs in base-n in ruby on rails?

Thanks!

Answer

apneadiving picture apneadiving · Jan 23, 2011

I'll check Ruby function but don't forget your basics: alt text

Prior to Ruby 1.9:

> Math::log(234504) / Math::log(5)
=> 7.682948083154834

In Ruby 1.9 and later, the second argument was introduced:

> Math::log(234504, 5)
=> 7.682948083154834