6

I use Meteor. It uses Javascript on both the server and client.

When I run Math.sin(356644061314425) * 10000 i get:

-9986.46139381927 on the server and

-9986.46115497749 on the client / browser / app

Why is this? How can I prevent this?

EDIT: The proposed duplicate questions refer to degrees / radians. I think mine is more a runtime problem.

Obiwahn
  • 2,677
  • 2
  • 26
  • 36
  • Set it to show 3 decimal places ;) – Adam Buchanan Smith Oct 27 '15 at 16:27
  • it is using floats probably. You know, floats are not precise at some point. – Gonzalo.- Oct 27 '15 at 16:28
  • Possible duplicate of [Unusual Math with incorrect results?](http://stackoverflow.com/questions/8691800/unusual-math-with-incorrect-results) – Adam Buchanan Smith Oct 27 '15 at 16:29
  • Plenty of answers right now if you google it.... – Adam Buchanan Smith Oct 27 '15 at 16:30
  • How can you get that value? `sin` returns values between `-1` and `1`. Either way, `sin` is an aproximation and can't be guaranteed to be equal. You should always take comparing numbers: http://stackoverflow.com/questions/3343623/javascript-comparing-two-float-values – Juan Oct 27 '15 at 16:30
  • `sin()` should return values in [-1,1]. You're taking the sine of a huge value. My guess is different FPUs on the server and client or differences in the js runtime. Try different browsers as well, if you see differences between browsers on the same machine then it's js. – Michel Floyd Oct 27 '15 at 16:34
  • Obviously the OP is multiplying the answer by 10000. For interest, my Firefox gives -9986.46139381927, while my chrome gives -9986.46115497749 for Math.sin(356644061314425)*10000. So I suppose it's a matter of different runtimes. – Chris Lear Oct 27 '15 at 16:37
  • 1
    My opera gives -9986.46139381927, as does Edge and Safari. Google's calculator gives -9986.46115. Windows calculator gives -9986.4611549774901487819562311456. So it looks like Chrome (the odd browser out) might be more accurate. – Chris Lear Oct 27 '15 at 16:47

1 Answers1

7

I think the answer to "How do I prevent this?" is "you can't".

The answer to "Why is this?" is that the javascript implementation of Math.sin is not determined.

See http://www.ecma-international.org/ecma-262/5.1/#sec-15.8.2.16

Specifically "sin (x) Returns an implementation-dependent approximation to the sine of x. The argument is expressed in radians." (my italics).

But my experimentation suggests that modern browsers currently only use one of two implementations, with Chrome being different to (and seemingly more accurate than) other browsers.

Chris Lear
  • 6,592
  • 1
  • 18
  • 26
  • 2021 update: Opera, Firefox, Chrome and Edge now all give the same result of `-9986.46115497749` for `Math.sin(356644061314425) * 10000` – Chris Lear May 25 '21 at 09:26