Tuesday, April 22, 2025

JavaScript `Math.cos()` Method – Explained with Examples

   

The `Math.cos()` method in JavaScript is used to return the cosine of a number. This number must be in radians, not degrees. The result will always be a numeric value between -1 and 1, representing the cosine of the given angle.

Syntax:

Math.cos(x)
`x` is a number in radians.

Important Note:

To convert degrees to radians, use the formula:

`radians = degrees * (Math.PI / 180)`

JavaScript `Math.cos()` Examples:

<script>
    // Converting degrees to radians before using Math.cos()
    var one = Math.cos(45 * (Math.PI / 180));
    document.writeln('Cosine of 45°: ' + one + '<br><br>');

    var two = Math.cos(90 * (Math.PI / 180));
    document.writeln('Cosine of 90°: ' + two + '<br><br>');

    var three = Math.cos(-1); // -1 is already in radians
    document.writeln('Cosine of -1 radian: ' + three + '<br><br>');

    var four = Math.cos(2 * Math.PI);
    document.writeln('Cosine of 2π radians: ' + four + '<br><br>');
</script>

Output:

Cosine of 45°: 0.7071067811865476

Cosine of 90°: 6.123233995736766e-17 (approximately 0)

Cosine of -1 radian: 0.5403023058681398

Cosine of 2π radians: 1

No comments:

Post a Comment