Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i use Math.sin() in javascript to get correct answer? [duplicate]

When I use Math.sin(90) for calculating Sine of 90 degrees in javascript it returns 0.8939966636005565, but sin(90) is 1. Is there a way to fix that? I need accurate values for any angle.

<!DOCTYPE html>
<html>
<body>
    <p id="demo">Click the button calculate value of 90 degrees.</p>
    <button onclick="myFunction()">Try it</button>
<script>
function myFunction(){
    document.getElementById("demo").innerHTML=Math.sin(90);
}
</script>

like image 725
JaSamSale Avatar asked Mar 30 '14 14:03

JaSamSale


People also ask

How do you use sine in JavaScript?

The Math. sin() method in Javascript is used to return the sine of a number. The Math. sin() method returns a numeric value between -1 and 1, which represents the sine of the angle given in radians.

How do you calculate sin in math?

The sine is equal to the ratio of the side opposite the angle and the hypotenuse of the right-angled triangle they define. The angle must be measured in radians. To convert an angle measured in degrees to its radian equivalent, multiply the angle by π, represented in Squirrel by the constant PI , and divide by 180.

How do you do cosine in JavaScript?

The Math. cos() method returns a numeric value between -1 and 1, which represents the cosine of the angle. Because cos() is a static method of Math , you always use it as Math. cos() , rather than as a method of a Math object you created ( Math is not a constructor).

Does sin have a value?

Also, ∞ is undefined thus, sin(∞) and cos(∞) cannot have exact defined values. However, sin x and cos x are periodic functions having a periodicity of (2π). Thus, the value of sin and cos infinity lies between -1 to 1. There are no exact values defined for them.


2 Answers

Math.sin expects the input to be in radian, but you are expecting the result of 90 degree. Convert it to radian, like this

console.log(Math.sin(90 * Math.PI / 180.0));
# 1

As per the wikipedia's Radian to Degree conversion formula,

Angle in Radian = Angle in Degree * Math.PI / 180
like image 191
thefourtheye Avatar answered Oct 16 '22 17:10

thefourtheye


The sin function in Javascript takes radians, not degrees. You need to convert 90 to radians to get the correct answer:

Math.sin(90 * (Math.PI / 180))
like image 26
sjf Avatar answered Oct 16 '22 15:10

sjf