1

When I evaluate either of these statements in the stable version of Chrome (Version 32.0.1700.107) I get a value that's not Infinity.

Math.tan(90 * Math.PI / 180)
16331778728383844

Math.tan(Math.PI/2)

16331778728383844

What is the root of this problem? I am certain that Math.tan is not reassigned a new value elsewhere in my code.

deadboy
  • 849
  • 2
  • 9
  • 28
  • This might help: http://math.stackexchange.com/questions/536144/why-does-the-google-calculator-give-tan-90-degrees-1-6331779e16 – Derek 朕會功夫 Jun 27 '14 at 17:31
  • If I open a console and run either in my Chrome (v37) I get `Infinity` as expected. Try it on a different page to the one with the problem. if there are issues then you must have something else in your code messing things up. – Rich Bradshaw Jun 27 '14 at 17:31
  • 1
    + 1 to counteract the down votes. The question is valid imho. – fmsf Jun 27 '14 at 17:32
  • 2
    Check out the [answers here](http://stackoverflow.com/questions/24455775/why-does-node-not-evaluate-math-tanmath-pi-2-to-infinity-but-chrome-v8-does). – admdrew Jun 27 '14 at 17:33
  • 1
    @Wooble - That is not related to this question. – Derek 朕會功夫 Jun 27 '14 at 17:35
  • +1, this question is deceptively simple. ) Still it seems to be explained well enough in the linked thread (I've upvoted @Niet's answer, for me it's as close to explanation as can be), hence the 'duplicate' marking. – raina77ow Jun 27 '14 at 17:51

2 Answers2

2

The rounding errors. For the same reason Math.cos(Math.PI/2) won't give you 0.

UPDATE: Actually it gives you 0 on the latest version of Chrome/Node - but judging from this open issue, it's actually considered a regression in V8. Still (and it's mentioned in the issue's discussion), Math.sin/cos are implementation-dependent approximations, and expecting those to behave in a uniform way all across the board is, sadly, overoptimistic.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
1

It's worth noting here that in newer version of Chrome, the (perhaps expected) issues to do with floats are actually not present.

This isn't the case in Firefox at the moment, so if you are writing code where this matters, be careful.

Output in Chrome 37

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
  • No, I can replicate in Firefox and Safari. I think V8 uses a better low level system for this. – Rich Bradshaw Jun 27 '14 at 17:39
  • Actually, [this bug](https://code.google.com/p/v8/issues/detail?id=3006) makes me think Chromium has a regression in trigonometric functions (note that the bug is _accepted_). BTW, Node.js also shows the non-zero value for `Math.cos(Math.PI/2)`. – raina77ow Jun 27 '14 at 17:41
  • Just remembered that I don't use the latest version of Node. ) It's `v0.10.23` for me; the answer linked in the comments shows `0` for `0.11` or something like that. – raina77ow Jun 27 '14 at 17:44
  • Yep, I'm on 0.10.25 and get the non Infinity version as well. – Rich Bradshaw Jun 27 '14 at 17:45