efarley - 2 months ago 8

Javascript Question

I'm trying to understand the math behind the Math.tan method but it doesn't make any sense. Can someone please explain to me how it works?

Firstly the mathematical formula to solve for a tangent angle is Tangent = Opposite/Adjacent. Which means I need to know two sides of the triangle to figure out the tangent angle. However the Math.tan method only accept a single argument in radians, not the length of two sides, so I don't understand how it's figuring out the angle of the tangent.

Next in examples they show passing impossibly huge radian values into the method and getting back a value. For example, W3 schools shows the example of

`Math.tan(90)`

How does this method work, what's happening behind the scenes that turns 90 radians into a tangent angle of -1.995200412208242

Answer

First let's talk about what a tangent is: Tangent is `y/x`

for the coordinate at a specific point (see this YouTube video for an example).

So if you want the tangent of pi over 2, on a graph, that's at a 90 degree angle, so the coordinate is `(0, 1)`

. Then you just divide `1/0`

.

However, `Math.tan`

isn't very precise. In Chrome 52, `Math.tan(Math.PI / 2)`

(from the video above) is `16331239353195370`

, even though it should evaluate to the `Infinity`

value in JavaScript (the mathematical value is actually undefined since it works out to `1/0`

).

According to this answer, the V8 implementation is:

```
function MathTan(x) {
return MathSin(x) / MathCos(x);
}
```

(As a side note: The value that Chrome actually outputs is larger than `Number.MAX_SAFE_INTEGER`

, which you can prove by running `Number.MAX_SAFE_INTEGER < Math.tan(Math.PI / 2) // => true`

, so Chrome takes it to be "close to infinity".)

The reason for the lack of a precise value is that pi is generally represented as a fixed value (since we have limitations in computer memory), even though it should be "Infinity" or "undefined" outside of the context of programming. For example, in my browser, `Math.PI`

is fixed at `3.141592653589793`

.