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:
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.
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.
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.
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.
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.
Powered by WPeMatico