PHP cos() function


The cos() function in PHP is used to calculate the cosine of a given angle, which is expected to be in radians. The cosine function is a fundamental trigonometric function that computes the ratio of the length of the adjacent side of a right-angled triangle to the length of the hypotenuse.

Syntax:

cos($angle_in_radians)

Parameters:

  • $angle_in_radians: The angle in radians for which you want to calculate the cosine value.

Return Value:

  • The function returns the cosine of the given angle as a float.

Important Note:

Since the cos() function expects the angle in radians, if your angle is in degrees, you need to convert it to radians using the deg2rad() function.

Example 1: Calculating Cosine of an Angle in Radians

<?php $angle_in_radians = pi() / 3; // pi/3 radians (60 degrees) // Calculate cosine of the angle $cosine_value = cos($angle_in_radians); echo $cosine_value; ?>

Output:

0.5

In this example, cos(π/3)\cos(\pi/3) or cos(60)\cos(60^\circ) is 0.5.

Example 2: Calculating Cosine of an Angle in Degrees

To calculate the cosine of an angle given in degrees, convert it to radians using deg2rad().

<?php $angle_in_degrees = 45; // Convert degrees to radians $angle_in_radians = deg2rad($angle_in_degrees); // Calculate cosine of the angle $cosine_value = cos($angle_in_radians); echo $cosine_value; ?>

Output:

0.70710678118655

Here, cos(45)\cos(45^\circ) is approximately 0.7071.

Practical Usage:

  • The cos() function is widely used in trigonometric calculations, particularly in geometry, physics, and engineering.
  • It's useful for calculating the horizontal component of a vector, modeling periodic functions (e.g., waves, oscillations), or working with angles in various fields.

Example 3: Cosine in Physics (Projectile Motion)

In physics, the horizontal distance xx traveled by a projectile launched at an angle θ\theta with an initial velocity vv can be calculated as:

x=vtcos(θ)x = v \cdot t \cdot \cos(\theta)

Where:

  • vv is the initial velocity,
  • tt is the time of flight,
  • θ\theta is the launch angle.
<?php $v = 50; // Initial velocity in meters per second $t = 5; // Time in seconds $angle_in_degrees = 30; // Launch angle in degrees // Convert degrees to radians $angle_in_radians = deg2rad($angle_in_degrees); // Calculate horizontal distance $distance = $v * $t * cos($angle_in_radians); echo "The horizontal distance is: " . $distance . " meters"; ?>

Output:

The horizontal distance is: 216.50635094611 meters

Summary:

  • cos() calculates the cosine of an angle in radians.
  • If the angle is in degrees, use deg2rad() to convert it to radians before using cos().
  • It is widely used in mathematical, physical, and engineering applications to compute angles, directions, or periodic functions.