Trigonometry is one of the most important concepts in Mathematics. PHP cos is an inbuilt Math Function in PHP. It calculates the cosine value of a number in radians. The cosine value oscillates between -1 and 1. In this article, we will discuss the PHP cos Function. Also, we will discuss an example of using it.
float cos ($value)
The function expects only one parameter. The number for which you want to find the cosine value is the input to the function. Also, the input value is in radians.
The function returns a float value which is the cosine value of the input number. Also, the value is in the range -1 to 1.
Input: cos(0) Output: 1 Input: cos(M_PI) Output: -1 Input: cos(1) Output: 0.54030230586814 Input: cos(M_PI_2) Output: 6.1232339957368E-17
For instance, consider the following example of using the function.
<?php echo cos(0); echo cos(M_PI); echo cos(1); echo cos(M_PI_2); ?>
The above example prints the following:
Output: 1 -1 0.54030230586814 6.1232339957368E-17
Why is cos pi/2 Not Zero?
From the concepts of trigonometry, we know that cos(pi/2) is 0. However, in PHP Cos pi/2 (or M_PI_2) does not return 0 because pi is not exactly π. The Pi is an irrational number which even with the highest level of precision can only be approximated till some decimal level. Therefore, the value of cos pi/2 is not zero.
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.