Monday, January 25, 2010

Logarithm to any base in ruby

Ruby's Math module includes functions for a natural log (log to the base e) and the common log (log to the base 10). If you have to have a log to an arbitrary base, you have to write your own. Doing so is trivial.

#log a to the base b
def log_base(a, b)
return (Math.log(a)/Math.log(b))
end
log_base(10,10) # 1.0
log_base(100,10) # 2.0
log_base(20,10) # 1.30102999566398
view raw log_base.rb hosted with ❤ by GitHub


I will probably explain the theory behind this another day.