2.7. Taking Logarithms

Problem

You want to take the logarithm of a number.

Solution

For logs using base e (natural log), use log( ):

$log = log(10);          // 2.30258092994

For logs using base 10, use log10( ):

$log10 = log10(10);      // 1

For logs using other bases, use pc_logn( ):

function pc_logn($number, $base) {
    return log($number) / log($base);
}

$log2  = pc_logn(10, 2); // 3.3219280948874

Discussion

Both log( ) and log10( ) are defined only for numbers that are greater than zero. The pc_logn( ) function uses the change of base formula, which says that the log of a number in base n is equal to the log of that number, divided by the log of n.

See Also

Documentation on log( ) at http://www.php.net/log and log10( ) at http://www.php.net/log10.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.