Previous Section  < Day Day Up >  Next Section

13.12 Advanced Math

On most systems, the PHP interpreter can handle integers between -2147483648 and 2147483647 (that's 2 billion), and floating-point numbers between -10^308 and 10^308. If you're writing scientific or other math-intensive applications, such as figuring out each citizen's portion of the U.S. National Debt, that might not be good enough. The BCMath and GMP extensions provide more advanced mathematical capabilities. The GMP extension is more capable, but not available on Windows. Example 13-15 uses the BCMath extension to compute the hypotenuse of a really big right triangle.

Example 13-15. Doing math with the BCMath extension
// Figure out hypotenuse of a giant right triangle

// The sides are 3.5e406 and 2.8e406



$a = bcmul(3.5, bcpow(10, 406));

$b = bcmul(2.8, bcpow(10, 406));



$a_squared = bcpow($a, 2);

$b_squared = bcpow($b, 2);



$hypotenuse = bcsqrt(bcadd($a_squared, $b_squared));



print $hypotenuse;

The number that Example 13-15 prints is 407 digits long.

Example 13-16 shows the same calculation with the functions in the GMP extension.

Example 13-16. Doing math with the GMP extension
$a = gmp_mul(35, gmp_pow(10,405));

$b = gmp_mul(28, gmp_pow(10,405));



$a_squared = gmp_pow($a, 2);

$b_squared = gmp_pow($b, 2);



$hypotenuse = gmp_sqrt(gmp_add($a_squared, $b_squared));



print gmp_strval($hypotenuse);

Read about BCMath and GMP in O'Reilly's PHP Cookbook, Recipe 2.13; and in the PHP Manual (http://www.php.net/bc and http://www.php.net/gmp).

    Previous Section  < Day Day Up >  Next Section