21

Javascript Math trigonomerial methos return wrong results. Try

alert(Math.sin(Math.PI));

it doesn't return 0.

Maybe problem is with javascript decimal number precision. Is there any workoround to get correct results?

mleko
  • 11,650
  • 6
  • 50
  • 71
tomas.teicher
  • 913
  • 3
  • 13
  • 26
  • Is it acceptable to your side to round off the result? `1.2246467991473532e-16` is quite small and rounding it off will convert it to `0`. Well, JS's `Math` is not developed for high precision math :-( – OnesimusUnbound Jun 03 '11 at 06:17
  • 1
    possible duplicate of [Floating point numbers and JavaScript modulus operator](http://stackoverflow.com/questions/3966484/floating-point-numbers-and-javascript-modulus-operator) and probably a couple hundred others. – mu is too short Jun 03 '11 at 06:22
  • woes of finite precision... (even though `1-Math.pow(Math.cos(Math.PI),2) == 0`) – CAFxX Jun 03 '11 at 06:49
  • 1
    Maybe you should read "What Every Computer Scientist Should Know About Floating Point Arithmetic": http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html – duffymo Jun 03 '11 at 09:17
  • just noticed this. Just nuts. You would think they could have friggin optimized `sin` to give the right answer. – George Mauer Apr 30 '16 at 17:10

2 Answers2

16

It's very, very close to zero, though. (~ 10^-16)

And alert(Math.sin(Math.PI/2)) does return 1.

It's just one of things you have to be careful of when dealing with floating point arithmetic. Rounding errors pop up all over the place.

Andrew Cooper
  • 32,176
  • 5
  • 81
  • 116
4

you can use

Math.sin(Math.PI).toFixed(3) // "0.000"

Examples:

const cos = (a) => Math.cos(Math.PI * a / 180); cos(90) // 6.123233995736766e-17

then you can use .toFixed()

cos(90).toFixed(3) // "0.000"

Note

.toFixed() returns string, so you can parse it to float using parseFloat()

parseFloat(cos(90).toFixed(3)) // 0.000

Davenchy
  • 47
  • 6