PHP - Number: Calculating Logarithms



PHP Number Tips - Part 13: If you want to find the logarithm of a number, you can use PHP's log( ) and log10( ) function such as:
<?php
//find natural log of 6
//result: "Natural log of 6 is 1.79175946923. "
$logBaseE = log(6);
echo "Natural log of 6 is $logBaseE. ";

//find base-10 log of 5
//result: "Base10 log of 5 is 0.698970004336."
$logBase10 = log10(5);
echo "Base10 log of 5 is $logBase10.";
?>

Logarithms is useful when you are solving differential equations and most of the scientific calculators enable you to easily calculate the natural and base -10 logarithm of any number. PHP's log( ) and log10( ) is no different. To calculate the logarithm for any other base, you would normally use the logarithmic property log YX = log bX / log bY and in PHP, you can instead simply specify the base as a second parameter to log( ) as the following:

<?php
//find binary (base-2) log of 10
//result: "Binary log of 10 is 3.32192809489"
$logBase2 = log(10, 2);
echo "Binary log of 10 is $logBase2";
?>

The exponential function does the reserve of the natural logarithmic function and is expressed in PHP through the exp( ) function as follows:

<?php
//find e ^ $num
//result: "Exponent of 0.69315 is 2"
$exponentE = exp(0.69315);
echo "Exponent of 0.69315 is " . round($exponentE, 2);
?>




Tag: number. calculation, logarithm Category: Post : March 16th 2008 Read: 543 Bookmark and Share

blog comments powered by Disqus