Search code examples
javascriptnode.jsmathv8infinity

Why does node not evaluate Math.tan(Math.PI/2) to Infinity but Chrome V8 does?


When running this in a node command-line interface:

> Math.tan(Math.PI/2)
16331778728383844 

But in Chrome:

> Math.tan(Math.PI/2)
Infinity

Aren't both using the same V8 engine?

Node's result is not even equal to the maximum "integer" value in JavaScript.


Solution

  • If you look at the v8 implementation of the Math object, you see:

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

    Indeed, Math.cos(Math.PI/2) returns an unusual value in Node as well (in fact, the reciprocal of your unusual Math.tan result):

    > Math.cos(Math.PI/2)
    6.123031769111886e-17  // in Chrome, this is 0
    

    So, your question reduces to: Why is Math.cos(Math.PI/2) non-zero in Node <=0.10.24?

    This is difficult to answer. The implementation of sine and cosine are supplied by a math-heavy function called TrigonometricInterpolation, which relies on a reverse lookup table of 1800 sample values generated by C++ code, code which is itself generated a Python script when v8 is first installed.

    It is also worth noting, however, that the current trig lookup table code very recently replaced an older lookup table, so the current release of Node may not be using the most recent trig lookup table (since new code arrived in v8 on Nov. 22, 2013, but the only pull from v8 into Node prior to the 0.10.24 release in December 2013 was on Nov 11, 2013, eleven days prior to the change). Chrome probably is using up-to-date code, while current stable Node is using different trigonometric code.