Trigonometry, Random Numbers and More With Built-in PHP Math Functions
Basic maths is used a lot during programming. We need to frequently compare, add, multiply, subtract and divide different values when writing code.
Sometimes, the maths required in a program can be more involved. You might need to work with logarithmic, trigonometric or exponential functions. In this tutorial, I’ll discuss how to use each of these functions in PHP, with examples.
This tutorial will introduce you to the built-in math functions in PHP for doing trigonometry, exponentiation, and logarithm calculations. We’ll also look at rounding and generating random numbers.
Trigonometric Functions in PHP
You can calculate the value of sine, cos and tangent of different angles given in radians using
tan($angle). They all return
float values, and the angle measure passed to them is in radians.
This means that when you simply calculate
tan(45), you won’t get 1 as output, because you will actually be calculating the value of tangent at 45 radians, which is about 2,578 degrees. Luckily, PHP has two very useful functions for converting radians to degrees and vice versa. These functions are
deg2rad(). So, if you actually want to calculate the value of the tangent of 45 degrees, you will have to write
It is noteworthy that there is no direct PHP function to calculate the value of
cot(). However, these values are just reciprocals of
tan(), so you can still calculate their values indirectly.
You can also do the inverse and calculate the angle at which a trigonometric angle has a particular value. These functions are called
atan(). One thing you have to remember is that the values of sin and cos can never go beyond the range of -1 to 1 for any angle. This means that
acos() can only accept values in the range -1 to 1 as valid arguments. A value outside this range will give you NaN.
Trigonometry has a lot of applications like determining the trajectory of a projectile or the heights and distances of different objects, so having access to these functions is definitely helpful if you are writing code that simulates these situations.
These functions are also very helpful when you want to draw different elements using radial and angular values. Let’s say you want to draw a pattern of circles around a larger circle at a uniform distance. If you have read the PHP GD Shapes tutorial on Envato Tuts+, you probably remember that drawing any shapes will require you to pass coordinates in the form of x, y coordinates, but drawing circular patterns is easier with polar coordinates.
Using these trigonometric functions in this case will help you draw the desired figures using
cos() to convert polar coordinates to cartesian form. Here is an example:
<?php $image = imagecreatetruecolor(800, 600); $bg = imagecolorallocate($image, 255, 255, 255); imagefill($image, 0, 0, $bg); $radius = 80; for($i = 0; $i
The following image shows the final result of the above PHP code.
Exponential and Logarithmic Functions
PHP also has some exponential and logarithmic functions. The
exp($value) function will return the constant e raised to the power of float
$value. Similarly, you can calculate the logarithm of a given number to any base using the
log($arg, $base) function. If the
$base is omitted, the logarithm will be calculated using the natural base e. If you want to calculate the logarithm of a number to base 10, you can simply use the function
One more function that you might find useful is
pow($base, $exp), which returns
$base raised to the power of
$exp. Some of you might prefer to use the
** operator. The expression
$a**$b will give the same result as
pow($a, $b). However, you might get incorrect results in certain situations with
$a**$b. For example,
-1**0.5 will give you -1, which is incorrect. Calculating the same expression using
pow(-1, 0.5) will give the correct value, NaN.
Other Useful Mathematical Functions
There are a lot of other important mathematical functions as well. You can round fractions or decimal numbers up to the nearest integer using the
ceil(float $value) function. This will convert both 2.1 and 2.9 to 3. Similarly, you can round fractions or decimal numbers down to the nearest integer using the
floor(float $value) function. It will change both 2.1 and 2.9 to 2.
These functions are good for rounding up the results of different calculations easily. Let’s say you need to know how many persons a hall can accommodate based on its area. Your final answer after the division will most probably be a decimal number, but you can’t divide people into fractions, so the right answer would be the floor value of the calculated value.
You will often want to round a number up or down to the nearest integer. For example, you might want to change 2.1 to 2 but 2.9 to 3. This can be done easily using the
round($value, $precision, $mode) function. The
$precision parameter determines the number of decimal places to round to. The default value of 0 will simply return integers. The third
$mode parameter is used to determine what happens if the number you want to round lies exactly in the middle. You can use it to specify if 3.5 should be changed to 3 or 4.
Minimum and Maximum
PHP also has two functions called
max($values) to help you determine the lowest and highest values in a set or array of numbers. These functions can accept different kinds of parameters like two arrays and a string. You should take a look at the documentation to see how they would be compared.
You can also perform integer division in PHP using the
intdiv($dividend, $divisor) function. In this case, only the integral part of the quotient is returned after a division. Similarly, you can also get the remainder or modulo after the division of two arguments using the
fmod($dividend, $divisor) function. The returned value will always be less than the
$divisor in magnitude.
There are some other useful functions like
is_infinite($val) which can be used to determine if the value is a number and, if it is a number, whether it is finite or infinite. Remember that PHP considers any value that is too big to fit in a float to be infinite. So
is_finite() will return
true for 100 factorial but
false for 1000 factorial.
Generating Random Numbers in PHP
Random numbers prove to be quite useful in a number of situations. You can use them to generate “random” data for your application or to spawn enemy instances in games, etc. It is very important to remember that none of the functions we discuss in this section generate cryptographically secure random numbers. These functions are only meant to be used in situations where security is not an issue, like showing random greeting texts to repeat visitors or for generating random statistical data.
rand($min, $max) and
mt_rand($min, $max) can generate positive random integers between given values including the
$max value. When the functions are called without any parameters, they generate random numbers between 0 and
getrandmax(). You can
echo the value of
getrandmax() to see the maximum possible random number that these functions can generate on your platform.
mt_rand() is 4 times faster than
rand() and returns false if
$max is less than
$min. Starting from PHP 7.1.0,
rand() has actually been made an alias of
mt_rand(). The only difference is that
rand() still doesn’t give an error if
$max is less than
$min to maintain backward compatibility.
Here is a loop to generate random values between 0 and 100 a million times. As you can see, the values 0, 50 and 100 are generated approximately 10,000 times with slight fluctuations.
<?php $rand_values = ; $sum = 0; $count = 1000000; for($i = 0; $i
Both these functions also have their own seeder functions called
mt_srand() to provide a seed for the random number generators. You should just keep in mind that you only call
mt_srand() once in your program. Calling them before every call to
mt_rand() will give you the same “random” numbers every time.
PHP comes with a lot of built-in functions that should meet all your day-to-day computation needs. You can use these functions to do slightly more complicated calculations like GCD, LCM and factorials yourself.
There are just a couple of things you should remember when using these functions. For example, the value returned by functions like
ceil() is an integer, but it is still a float. Similarly, all trigonometric functions expect their angles to be given in radians. You will get incorrect results if you pass them an angle value that you wanted to be treated as a degree measure. So make sure you check the return value and expected arguments of all these functions in the documentation.