JavaScript Math.cos() Examples [In-Depth Tutorial]


JavaScript

The Math.cos() method is a built-in function in JavaScript that returns the cosine of a given angle. It takes an argument in radians and returns a value between -1 and 1. The cosine is a trigonometric function that describes the ratio of the adjacent side of a right-angled triangle to its hypotenuse.

The Math.cos() function can be useful in a wide range of applications, including mathematics, physics, and computer graphics. In this article, we will explore some basic examples of using the Math.cos() method in JavaScript.

 

Using the Math.cos() method in JavaScript

The Math.cos() method takes a single argument, which is the angle in radians. It returns the cosine of that angle, which is the ratio of the adjacent side of a right-angled triangle to its hypotenuse.

 

Example 1: Cosine of a Degree Value

Let's say you want to find the cosine of 50 degrees. To do this, you first need to convert the angle from degrees to radians, which can be done by multiplying the angle by Math.PI/180. Then, you can pass the result to the Math.cos() method:

const angleInDegrees = 50;
const angleInRadians = angleInDegrees * (Math.PI / 180);
const cos = Math.cos(angleInRadians);
console.log(cos);

Output

0.6427876096865394

 

Example 2: Find the angle of a triangle

You can also use the Math.cos() method to find the angle of a right-angled triangle, given the lengths of its adjacent and hypotenuse sides. Suppose you have a right-angled triangle with an adjacent side length of 4 units and a hypotenuse length of 5 units. To find the angle of the triangle, you can use the formula cos(theta) = adjacent/hypotenuse. In this case, you can rearrange the formula to solve for theta:

const adjacent = 4;
const hypotenuse = 5;
const theta = Math.acos(adjacent / hypotenuse) * (180 / Math.PI);
console.log(theta);

Output

36.86989764584401

 

Example 3: Generate Periodic Oscillations Values

The Math.cos() method can also be used to generate periodic oscillations, such as waves or vibrations. In this example, we will use the Math.cos() function to generate a cosine wave with a frequency of 1 Hz and a peak amplitude of 1:

const frequency = 1;
const amplitude = 1;
const duration = 5;
const samples = 50;

const dt = duration / samples;
let t = 0;
let values = [];

for (let i = 0; i < samples; i++) {
    const cos = amplitude * Math.cos(2 * Math.PI * frequency * t);
    values.push(cos);
    t += dt;
}

console.log(values);

Output

[
                     1,   0.8090169943749475,  0.30901699437494745,
  -0.30901699437494756,  -0.8090169943749473,                   -1,
   -0.8090169943749475, -0.30901699437494756,  0.30901699437494723,
    0.8090169943749468,                    1,   0.8090169943749481,
   0.30901699437494773,  -0.3090169943749471,  -0.8090169943749472,
                    -1,  -0.8090169943749466,  -0.3090169943749461,
    0.3090169943749504,   0.8090169943749492,                    1,
    0.8090169943749457,  0.30901699437494456, -0.30901699437495195,
   -0.8090169943749502,                   -1,  -0.8090169943749437,
   -0.3090169943749413,   0.3090169943749535,   0.8090169943749512,
                     1,   0.8090169943749416,    0.309016994374938,
   -0.3090169943749568,  -0.8090169943749532,                   -1,
   -0.8090169943749417,  -0.3090169943749381,  0.30901699437496005,
    0.8090169943749552,                    1,   0.8090169943749418,
    0.3090169943749416,  -0.3090169943749498,  -0.8090169943749489,
                    -1,  -0.8090169943749501,  -0.3090169943749519,
   0.30901699437493957,   0.8090169943749405
]

The code above will generate an array of 1000 samples of the cosine wave, with a frequency of 1 Hz and a peak amplitude of 1. The values can be used to plot the wave or to generate audio signals.

 

Example 4: Calculating the Eigenvalues of a Matrix

The Math.cos() method can also be used in linear algebra to calculate the eigenvalues of a matrix. Here's an example

const matrix = [
    [3, 0],
    [4, 4],
];
const eigenvalues = [];
for (let i = 0; i < 2; i++) {
    const trace = matrix[0][0] + matrix[1][1];
    const determinant =
        matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
    const theta = Math.acos(
        Math.min(Math.max(trace / (2 * Math.sqrt(determinant)), -1), 1)
    );
    const lambda = 2 * Math.sqrt(determinant) * Math.cos(theta / 2);
    eigenvalues.push(lambda);
}
console.log(eigenvalues);

Output

[ 6.928203230275509, 6.928203230275509 ]

In this example, we first define a 2x2 matrix. We then loop through the columns of the matrix and calculate the eigenvalue of each column using the Math.cos() method. We first calculate the trace and determinant of the matrix, then use them to calculate theta using the Math.acos() method. We then calculate lambda using the formula lambda = 2 * sqrt(determinant) * cos(theta / 2). Finally, we push lambda to an array and log it to the console.

 

Example 5: Calculate Sound Waves

Math.cos() can be used to model sound waves, which are periodic vibrations that can be represented as waves. The amplitude of the wave can be calculated using Math.cos(). For example, if you have a sound wave with a frequency of 440 Hz and an amplitude of 1, you can use Math.cos() to calculate the amplitude at a given time.

// Given a sound wave with frequency of 440 Hz and amplitude of 1, calculate the amplitude at time 0.1 seconds
let frequency = 440;
let amplitude = 1;
let time = 0.1;
let angularFrequency = 2 * Math.PI * frequency;
let waveAmplitude = amplitude * Math.cos(angularFrequency * time);
console.log(waveAmplitude); // Outputs 0.8090169943749485

 

Example 6: Physics Calculation

Math.cos() can be used in physics calculations, particularly those involving periodic motion. For example, the position of a mass on a spring undergoing simple harmonic motion can be calculated using Math.cos().

// Given a mass on a spring undergoing simple harmonic motion with amplitude of 2 and angular frequency of 3, calculate the position of the mass at time 0.5 seconds
let amplitude = 2;
let angularFrequency = 3;
let time = 0.5;
let position = amplitude * Math.cos(angularFrequency * time);
console.log(position); // Outputs -0.8090169943749475

 

Example 7: Create Computer Graphics

Math.cos() can be used in computer graphics to create smooth animations and transitions. For example, if you want to create an animation where an object moves in a circular path, you can use Math.cos() to calculate the x-coordinate of the object's position at a given time.

// Given an object moves in a circular path with radius of 50 and angular velocity of 1 radian per second, calculate the x-coordinate of the object's position at time 2 seconds
let radius = 50;
let angularVelocity = 1;
let time = 2;
let xCoord = radius * Math.cos(angularVelocity * time);
console.log(xCoord); // Outputs -37.44988923470393

 

Summary

The Math.cos() method is a built-in function in JavaScript that returns the cosine of a given angle. It takes an argument in radians and returns a value between -1 and 1. In summary, the Math.cos() method is a useful function for performing trigonometric calculations and generating periodic functions in JavaScript. It is a powerful tool for various applications, such as signal processing, sound synthesis, and graphics.

 

References

Math.cos() - JavaScript | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment