PHP Notes - Math Stuff
by D. W. Hyatt
PHP has lots of different math functions. It even has a set of functions
that do arbitrary precision arithmetic using strings. These can be extremely
powerful, but be considerate of our web server when asking it to do these
calculations since the Pentium system is trying to handle our average web
traffic of approximately 40,000 hits a day. Burdensome calculations
could slow down a number of other users.
Trigonometric Functions
Angle measurements are expressed in radians in most cases and the function
returns a double.
- sin($angle)
- cos($angle)
- tan($angle)
- asin($value)
- acos($value)
- atan($value)
- atan2($x-value $y-value) (returns angle portion in polar coordinates)
- deg2rad($degrees) (returns radians given degrees)
- rad2deg($radians) (returns degrees given radians)
- pi() (returns approximate value of pi_
Powers and Roots
There are a number of different functions relating to powers and roots in PHP.
Most return a double.
- sqrt($value)
- pow($base, $exponent)
- log($value) (natural log)
- log10($value) (log base 10)
- exp($power) ( ex )
Rounding Functions
Here are a few of the rounding type functions available in PHP.
- round($value) (round to nearest integer)
- abs($value) (absolute value)
- ceil($value) (ceiling)
- floor($value) (floor)
Arbitrary Precision Arithmetic
PHP has the ability to do arithmetic with numbers of arbitrary
precision. The operations are done with strings. It is similar
in some ways to the UNIX calculator bc, hence the prefix
to these functions. The number of decimals can be set by the
bcscale() function, or provided in the actual call to most of
the specific operations. The scale parameter is not required, and the default
values will be used.
- bcscale($decimals) (set the number of decimals places in the
precision)
- bcadd($left, $right, [$scale]) (add)
- bcsub($left, $right, [$scale]) (subtract)
- bcmul($left, $right, [$scale]) (multiply)
- bcdiv($left, $right, [$scale]) (divide)
- bcmod($left, $right) (modulo)
- bcsqrt($num, [$scale]) (sqare root)
- bccomp($left, $right, [$scale]) (compare - three answers: -1 left < right; 0 left = right; 1 left > right )
- bcpow($base, $power, [$scale]) (power )