[Solved] How does Math.tan(x) actually work? (Javascript) [closed]


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”.)

Edit

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.

10

solved How does Math.tan(x) actually work? (Javascript) [closed]