Erlang Central

Difference between revisions of "Logarithms"

From ErlangCentral Wiki

Line 67: Line 67:

Revision as of 23:12, 3 September 2006


You want to take a logarithm in various bases.


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

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

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

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)  =   --------- 
      n           log(n)


To find the base 10 logarithm of 1.82:

   log (1.82)  =   ----------- 
      10             log(10)

3> math:log(1.82) / math:log(10).

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) ]).

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).
6> io:format("~.16f~n", [logN(10, 1.82)]).