8

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!

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Scott Allen
  • 113
  • 2
  • 7

2 Answers2

15

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
Jeff Ward
  • 16,563
  • 6
  • 48
  • 57
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • 1
    this works in any base - not just to the base of e. just use the decadic logarithm instead of ln. – Femaref Jan 23 '11 at 22:31
  • 1
    Actually, it' even more general: `log_b1(x) = log_b2(x) / log_b2(b1)` (edit: in relatively plain english, what @Femaref said). –  Jan 23 '11 at 22:31
  • just couldn't come up with a resonable good notation for the bases. – Femaref Jan 23 '11 at 22:32
  • Ha, I had avoided dusting off my college textbooks! Thanks, this works great. I'm guessing then that there's no direct support for base-n in the log functions right now. – Scott Allen Jan 23 '11 at 22:42
  • Yep, I guess we should feel happy with that solution but I cannot be fully satisfied. Which version do you have? – apneadiving Jan 23 '11 at 22:57
  • Thanks steenslag - looks like it might be time for me to upgrade my Ruby. – Scott Allen Jan 24 '11 at 00:14
4

The other answer is correct of course, but in the interest of saving time, Math.log(n, base) works in Ruby >= 1.9

http://www.ruby-doc.org/core-2.0/Math.html#method-c-log

AlexQueue
  • 6,353
  • 5
  • 35
  • 44
  • I +1'd you because it's much more Rubyish, but if you look into `log(x, base)` source code, you'll see that it just winds up using the same relation: `d = log(d0); if (argc == 2) d /= log(RFLOAT_VALUE(base));`. So, using one call to function that anyway deals with arbitrary base is more efficient - it does one function call instead of two. – tkroman Jun 19 '13 at 18:18