O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.7. Taking Logarithms

Problem

You want to take the logarithm of a number, possibly a huge one.

Solution

Math.log calculates the natural log of a number: that is, the log base e.

	Math.log(1)                          # => 0.0
	Math.log(Math::E)                    # => 1.0
	Math.log(10)                         # => 2.30258509299405
	Math::E ** Math.log(25)              # => 25.0

Math.log10 calculates the log base 10 of a number:

	Math.log10(1)                          # => 0.0
	Math.log10(10)                         # => 1.0 
	Math.log10(10.1)                       # => 1.00432137378264 
	Math.log10(1000)                       # => 3.0
	10 ** Math.log10(25)                   # => 25.0

To calculate a logarithm in some other base, use the fact that, for any bases b1 and b2 , logb1(x) = logb2(x) / logb2(k).

	module Math
	  def Math.logb(num, base)
	    log(num) / log(base)
	  end
	end

Discussion

A logarithm function inverts an exponentiation function. The log base k of x,or logk(x), is the number that gives x when raised to the k power. That is, Math. log10(1000)==3.0 because 10 cubed is 1000.Math.log(Math::E)==1 because e to the first power is e.

The logarithm functions for all numeric bases are related (you can get from one base to another by dividing by a constant factor), but they're used for different purposes.

Scientific applications often use the natural log: this is the fastest log implementation in Ruby. The log base 10 is often used to visualize datasets that span many orders of magnitude, such as the pH scale for acidity and the Richter scale for earthquake intensity. Analyses of algorithms often use the log base 2, or binary logarithm.

If you intend to do a lot of algorithms in a base that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required