e r l a n g : c o o k b o o k

/ Erlang.NumberTakingLogs

This Web


WebHome 
WebChanges 
TOC
NewRecipe 
WebTopicList 
WebStatistics 

All Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Erlang Links


Erlang.org
Erlang Wiki
ErlMan
Erlang Wiki
The Jungerl
Erlang-fr.org
Joe Armstrong
Lambda the Ultimate

Erlang Web Ring


[Prev]: Joe Armstrong's Page
[Next]: Joe Armstrong's Page

Taking Logarithms

Problem

You want to take a logarithm in various bases.

Solution

For logarithms to base e, use the built-in math:log:

1> math:log( math:exp(2) ).
2.00000
2> math:log( 2.718281828 ).
1.000000

Note that log is often called ln in the mathematical literature.

Discussion

Erlang generally uses the underlying C runtime library of your chosen operating system to provide the various mathematical primitives, including the natural logarithm (ln, which is written log in Erlang). If you want logarithms in some other base you need to use the standard mathematical relation:

                  log(x)
   log (x)  =   --------- 
      n           log(n)

Example:

To find the base 10 logarithm of 1.82:

                    log(1.82)
   log (1.82)  =   ----------- 
      10             log(10)
3> math:log(1.82) / math:log(10).
0.260071

You may not be satisfied with five digits of precision. The Erlang command line interface makes a guess about what level of detail you want for display. You can override this via a call to format:

4> io:format("~.16f~n", [ math:log(1.82) / math:log(10) ]).
0.2600713879850748

Incidentally, note that "~n" is equivalent to "\n" in the various io module functions.

The most common bases besides e is 2 and 10. These logarithms are often called log2 and log10. While log10 is defined in the standard Erlang distribution, log2 is not. It can be trivially defined by:

log2(X) ->
  math:log(X) / math:log(2).
To avoid recomputation of the denominator at each call, one can use:
-define(log2denom, 0.69314718055994529).
log2(X) ->
    math:log(X) / ?log2denom.

A general version is:

logN(N, X) ->
    math:log(X) / math:log(N).

5> logN(10, 1.82).
0.260071
6> io:format("~.16f~n", [logN(10, 1.82)]).
0.2600713879850748


Comments about this recipe

Contributors

Based on work by BrentAFulgham, NeilVanDyke, and NoelWelsh.

Contributors

-- BrentAFulgham - 26 Aug 2004

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 110

 
 
Copyright © 2004 by the contributing authors. All material on the Erlang Cookbook web site is the property of the contributing authors.
This material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest