0

I've wrote some trace code to describe my problem.

GLOBALS.customTrace = "COS 0: " + String(Math.cos(0 * Math.PI / -180)) + "   //OK\n";
GLOBALS.customTrace += "SIN 0: " + String(Math.sin(0 * Math.PI / -180)) + "   //OK\n";
GLOBALS.customTrace += "COS 90: " + String(Math.cos(90 * Math.PI / -180)) + "   //WHY ?\n";
GLOBALS.customTrace += "SIN 90: " + String(Math.sin(90 * Math.PI / -180)) + "   //OK\n";
GLOBALS.customTrace += "COS 180: " + String(Math.cos(180 * Math.PI / -180)) + "   //OK\n";
GLOBALS.customTrace += "SIN 180: " + String(Math.sin(180 * Math.PI / -180)) + "   //WHY ?\n";
GLOBALS.customTrace += "COS 270: " + String(Math.cos(270 * Math.PI / -180)) + "   //WHY ?\n";
GLOBALS.customTrace += "SIN 270: " + String(Math.sin(270 * Math.PI / -180)) + "   //OK\n";

The code above...

...returning this output.

OUTPUT

I don't know how to handle with this? I don't need real values for whole angles, but i need real values of cos90, sin180, cos270 absolutely!

Also, there is another issue, but i feel it is a result of the real problem above. I'm using -180 and +180 both in this code, but both of them returning negative values.

GLOBALS.customTrace = "COS 270 with Math.PI / -180\n" + String(Math.cos(270 * Math.PI / -180)) + "   //IF THIS NEGATIVE...\n\n";
GLOBALS.customTrace += "COS 270: with Math.PI / +180\n" + String(Math.cos(270 * Math.PI / 180)) + "   //...WHY THIS NEGATIVE TOO ?\n";

The code above...

...returning this output

OUTPUT2

Bora Kasap
  • 392
  • 4
  • 12
  • Do you understand what sin and cos actually are in mathematics? – Marty Feb 13 '14 at 22:52
  • 1
    That's just floating point arithmetic. If it bugs you, print the results only up to 6 significant digits; you will see what you expect. – Ali Feb 14 '14 at 00:04
  • 1
    possible duplicate of [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – Ali Feb 14 '14 at 00:05
  • 1
    And the obligatory [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Teepeemm Feb 14 '14 at 03:43
  • So, problem not about trigonometry, the problem about precise numbers. Thanks. – Bora Kasap Feb 14 '14 at 07:01

1 Answers1

2

The reason is that Math.PI != π.

You can try toFixed(15) to get a precise value.

trace(String(Math.cos(90 * Math.PI / -180).toFixed(15)));
trace(String(Math.sin(180 * Math.PI / -180).toFixed(15)));
trace(String(Math.cos(270 * Math.PI / -180).toFixed(15)));
trace(String(Math.cos(90 * Math.PI / -180).toFixed(15)) == 0);
trace(String(Math.sin(180 * Math.PI / -180).toFixed(15)) == 0);
trace(String(Math.cos(270 * Math.PI / -180).toFixed(15)) == 0);

OutPut.

0.000000000000000
-0.000000000000000
-0.000000000000000
true
true
true
Tim
  • 2,121
  • 2
  • 20
  • 30