# 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 `sin($angle)`

, `cos($angle)`

and `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 2578 degrees. Luckily, PHP has two very useful functions for converting radians to degrees and vice-versa. These functions are: `rad2deg()`

and `deg2rad()`

. So, if you actually want to calculate the value of the tangent of 45 degrees, you will have to write `tan(deg2rad(45))`

.

It is noteworthy that there is no direct PHP function to calculate the value of `cosec()`

, `sec()`

or `cot()`

. However, these values are just reciprocals of `sin()`

, `cos()`

and `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 `asin()`

, `acos()`

and `atan()`

. One thing you have to remember is that the value of sin and cos never goes beyond the range of -1 to 1 for any angle. This means that `asin()`

and `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 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 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 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 `sin()`

and `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 < 12; $i++) { $col_ellipse = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200)); imagefilledellipse($image, 175 + 125*cos(deg2rad($i*30)), 175 + 125*sin(deg2rad($i*30)), 3*$radius/4, 3*$radius/4, $col_ellipse); imageellipse($image, 175 + 125*cos(deg2rad($i*30)), 175 + 125*sin(deg2rad($i*30)), 3.5*$radius/4, 3.5*$radius/4, $col_ellipse); $col_ellipse = imagecolorallocate($image, rand(0, 200), rand(0, 200), rand(0, 200)); imagefilledellipse($image, 575 + 150*cos(deg2rad($i*30)), 375 + 150*sin(deg2rad($i*30)), 3*$radius/4, 3*$radius/4, $col_ellipse); imageellipse($image, 575 + 150*cos(deg2rad($i*30)), 375 + 150*sin(deg2rad($i*30)), 3.5*$radius/4, 3.5*$radius/4, $col_ellipse); } $col_ellipse = imagecolorallocate($image, 255, 255, 255); imagefilledellipse($image, 175, 175, 275, 275, $col_ellipse); ?>

The following image shows the final result of above PHP code.

## Exponential and Logarithmic Functions

PHP also has some exponential and logarithmic functions as well. The `exp($value)`

function will return the constant **e** raised to the power of float `$value`

. Similarly, you can calculate the logarithm of 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 `log10($arg)`

.

One more function that you might find useful is `pow($base, $exp)`

which returns `$base`

raised to 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.

<?php echo log(1000, M_E); // 6.9077552789821 echo log(1000); // 6.9077552789821 echo log(1000, 10); // 3 echo log10(1000); // 3 echo pow(121, -121); // 9.6154627930786E-253 echo pow(121, 121); // 1.0399915443694E+252 echo pow(121, 1331); // INF ?>

## Other Useful Mathematical Functions

### Rounding Numbers

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 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 `min($values)`

and `max($values)`

to help you determine if the lowest and highest values in a set or array of numbers. These functions can accept different kinds of parameters like two arrays and string etc. You should take a look at the documentation to see how they would be compared.

<?php $hall_width = 120; $hall_length = 180; $per_person_area = 35; $hall_capacity = floor($hall_length*$hall_length/$per_person_area); // Output: The hall can only accommodate 925 people. echo 'The hall can only accommodate '.$hall_capacity.' people.'; $water_tank_volume = 548733; $bucket_volume = 305; $buckets_needed = ceil($water_tank_volume/$bucket_volume); // Output: We will need 1800 buckets of water to completely fill the tank. echo 'We will need '.$buckets_needed.' buckets of water to completely fill the tank.'; $marks = [49, 58, 93, 12, 30]; // Output: Minimum and maximum obtained marks in the exam are 12 and 93 respectively. echo 'Minimum and maximum obtained marks in the exam are '.min($marks).' and '.max($marks).' respectively.'; ?>

### Integer Division

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.

The are some other useful functions like `is_nan($value)`

, `is_finite($value)`

and `is_infinite($val)`

which can be used to determine 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.

The functions `rand($min, $max)`

and `mt_rand($min, $max)`

can generate positive random integers between given values including the `$min`

and `$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.

The function `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 10000 times with slight fluctuations.

<?php $rand_values = []; $sum = 0; $count = 1000000; for($i = 0; $i < $count; $i++) { $rand_values[$i] = mt_rand(0, 100); $sum += $rand_values[$i]; } $count_frequency = array_count_values($rand_values); // Output: 100 was randomly generated 9969 times. echo '100 was randomly generated '.$count_frequency[100].' times.'; // Output: 50 was randomly generated: 9994 times. echo '50 was randomly generated: '.$count_frequency[50].' times.'; // Output: 0 was randomly generated: 10010 times. echo '0 was randomly generated: '.$count_frequency[0].' times.'; // Output: Average of random values: 49.97295 echo 'Average of random values: '.($sum/$count); ?>

Both these functions also have their own seeder functions called `srand()`

and `mt_srand()`

to provide a seed for the random number generators. You should just keep in mind that you only call `srand()`

and `mt_srand()`

once in your program. Calling them before every call to `rand()`

and `mt_rand()`

will give you the same “random” numbers every time.

<?php srand(215); echo rand()."n"; // 330544099 srand(215); echo rand()."n"; // 330544099 srand(215); echo rand()."n"; // 330544099 echo rand()."n"; // 138190029 echo rand()."n"; // 1051333090 echo rand()."n"; // 1219572487 ?>

## Final Thoughts

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 `floor()`

and `ceil()`

is an integer but it is still a float. Similarly, all trigonometric functions accept 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.