Вопрос

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

Это было полезно?

Решение

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top