One important constant often used in calculations is Pi. PHP will return Pi to 14 decimals by default, however you can set it to be as precise as 20 decimals. Here are some example how to use Pi.
<?php
echo pi();
echo "<p>";
echo pi()*2;
echo "<p>";
echo M_PI;
echo "<p>";
echo M_PI*2;
?>
You may have noticed in the code above that we first use pi () and then use M_PI but they give the same results. There are also variations of M_PI that you can use directly without having to apply any other math to them. Here are some examples below:
M_PI_2 = Half of PI ()
M_PI_4 = One Quarter PI ()
M_1_PI =One divided by PI ()
M_2_PI = Two divided by PI ()
M_SQRTPI = Square root of PI ()
M_2_SQRTPI = Two Divided by the square root of PI ()
The next function we will explore is Sin () which of course returns the sine of the number you enter, as measured in radians. The number you input should also be in radians, but you will see in the code how you can input degrees. Here are some examples of using sin ():
<?php
echo sin(0);
echo "<p>";
echo sin(-1);
echo "<p>";
echo sin(deg2rad(90));
echo "<p>";
echo sin(deg2rad(45));
?>
As you can deduct from the code above deg2rad() converts degrees to radians. Since the input is expected in radians, this is useful for using these particular PHP functions if you are working with degrees. You can then convert back again with rad2deg(). Here are some examples:
<?php
echo rad2deg(M_PI);
echo "<p>";
echo rad2deg(M_PI_2);
echo "<p>";
echo rad2deg(4);
echo "<p>";
echo rad2deg(M_PI_4);
?>
The natural progression from sine is to also want to be able to calculate the cosine and tangent. These calculations also require an input in radians. They are calculated using the cos() and tan() functions. The example below should give you a better idea of how to use these functions.
<?php
echo cos(M_PI);
echo "<p>";
echo cos(deg2rad(360));
echo "<p>";
echo tan(M_PI_4);
echo "<p>";
echo tan(3);
?>
This article should give you a good understanding of making calculations related to triangles using PHP programming. You should also have an understanding of how to convert degrees to radians, and radians to degrees. How you now apply this information is up to you. You might try combining it with GD Library to create some graphs. We will learn about more mathematical functions as well as have a challenge question in the second part of this tutorial.

