PHP acos() function


The acos() function in PHP is used to calculate the arccosine (inverse cosine) of a given value. The arccosine function returns the angle (in radians) whose cosine is the specified value. This function is particularly useful when you have a cosine value and need to determine the corresponding angle.

Syntax:

acos($value)

Parameters:

  • $value: A float representing the cosine value for which you want to calculate the arccosine. The valid range for this value is from -1 to 1, inclusive.

Return Value:

  • The function returns the arccosine of the value in radians as a float. If the input value is outside the range of -1 to 1, the function will return NAN (not a number).

Example 1: Calculating Arccosine of a Value

<?php $value = 0.5; // Calculate arccosine $arccosine_value = acos($value); echo $arccosine_value; ?>

Output:

1.0471975511966

In this example, the arccosine of 0.5 is approximately π3\frac{\pi}{3} radians (or 60 degrees).

Example 2: Converting Arccosine to Degrees

To convert the result from radians to degrees, you can use the rad2deg() function.

<?php $value = 0.5; // Calculate arccosine in radians $arccosine_value = acos($value); // Convert radians to degrees $arccosine_degrees = rad2deg($arccosine_value); echo "Arccosine in degrees: " . $arccosine_degrees; ?>

Output:

Arccosine in degrees: 60

Example 3: Handling Invalid Input

If you provide a value outside the valid range of -1 to 1, the function will return NAN.

<?php $value = 2; // Out of range // Calculate arccosine $arccosine_value = acos($value); var_dump($arccosine_value); ?>

Output:

float(NAN)

Practical Usage:

  • The acos() function is commonly used in trigonometry and geometry when determining angles based on cosine values.
  • It is particularly useful in applications involving physics, engineering, and computer graphics where you might need to compute angles based on the ratios of sides.

Summary:

  • acos() calculates the arccosine (inverse cosine) of a value, returning the angle in radians.
  • Valid input values must be within the range of -1 to 1; otherwise, it returns NAN.
  • It is often used in conjunction with other trigonometric functions and for angle calculations in various applications.