You want to take a logarithm in various bases.

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

> (log (exp 2))
2
> (log 2.718281828)

Note that `log`

is often called `ln`

in the mathematical literature.

R5RS Scheme mandates the presence of natural logarithm (ln, which is written `log`

in Scheme). 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)

> (/ (log 1.82) (log 10))
0.2600713879850748

The most common bases besides e is 2 and 10. These logarithms are often
called `log2`

and `log10`

.

(define (log2 x)
(/ (log x) (log 2))
(define (log10 x)
(/ (log x) (log 10))

To avoid recomputation of the denominator at each call, one can use:

(define log2
(let ([denom (log 2)])
(lamdda (x)
(/ (log x) denom))))
(define log10
(let ([denom (log 10)])
(lamdda (x)
(/ (log x) denom))))

A general version is:

(define (log-n n x)
(/ (log x) (log n)))
> (log-n 10 1.82)
0.2600713879850748

Names modified per your suggestion. :-)

-- BrentAFulgham - 14 May 2004

I recently had to make this `log10`

. Too bad log information isn't preserved as part of exactness. :)

(define log10 (let ((ln-10 (log 10))) (lambda (n) (/ (log n) ln-10))))

I second the idea of a library for this. Actually, a couple of these
log functions *really* belong in MzLib? if not MzScheme default environment, IMHO.

-- NeilVanDyke - 14 May 2004

By the way, I'd suggest not planting the idea of using underscores in Scheme identifiers, even though underscore makes sense to TeX? users in the case of `log_e`

. How about `log-e`

or `loge`

?

-- NeilVanDyke - 14 May 2004

I reformatted the math formulas. I had an itch to change `log-n`

to `logn`

.
The `-`

will disturb my eye in a mathematical context. Besides, the names `log2`

and
`log10`

are the traditional ones.

-- BrentAFulgham - 14 May 2004