Spiderhund - 8 months ago 46

Javascript Question

I've run into a problem which is that Math.cos doesn't return a value between -1 and 1 but rather returns the value 6.123233995736766 when I pass the value 1.5707963267948966 to it.

The whole operation I'm going through is as follows.

- Start with 90 degrees.
- Convert to radians: 90 * Math.PI / 180 = 1.5707963267948966.
- Passing radians to Math.cos results in 6.123233995736766. The expected value is 0.9996242168594816.

This seems very odd to me. I've tested this in Google Chrome (51.0.2704.103 m), Firefox (47.0), and Internet Explorer (11.0.9600.17914). All seem to give me the same result.

Answer

Actually, the result is

```
Math.cos(90 * Math.PI / 180) == 6.123233995736766e-17
```

Note the `e-17`

here. The notation `eN`

after a number means "times 10^{N}".

That means that the calculated number is actually 6.123233995736766 × 10^{-17}, which is very actually a very *small* number and very close to the expected value 0.

The reason why there's a small difference here is that computers are really bad at computing functions such as sine and cosine *exactly*, so most of the time there will be a small (but negligible) difference between the computed value and the exact value.