Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...