• 0

[Java] Math.cos() and Math.sin()


Question

Ok Im having a problem with getting the value for deltaY below. deltaX works (90-270 = -180 convert that to radians to get -PI, cos(-PI) = -1.0).

Now deltaY should be 0 (sin (-PI) = 0) but i get -1.2246467991473532E-16 in java???

Did i miss something? My calculator gives me 0.

heading value is between 0 - 359, its represnets the direction in degrees with 0=north, 90 = east, 180=south, 270=west. This is the start of a 2D Car game.

int heading = car.getHeading(); // heading is 270

double deltaX = Math.cos(Math.toRadians(90-heading)); // -1.0

double deltaY = Math.sin(Math.toRadians(90-heading)); //-1.2246467991473532E-16 ????

Math.sin and cos input values are in radians.

degree to radians = (deg x PI)/180.

Link to comment
https://www.neowin.net/forum/topic/622071-java-mathcos-and-mathsin/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

There's two problems, rounding precision and the fact that PI in Java is not equal to pi (the infinitely long decimal number). More correctly, Java uses the FSIN instruction which is less accurate than the FDLIBM. Furthermore, the decimal number you got is extremely small, so unless you need it to 10^-16, then you might round to some precision and you'd get 0.

  • 0
There's two problems, rounding precision and the fact that PI in Java is not equal to pi (the infinitely long decimal number). More correctly, Java uses the FSIN instruction which is less accurate than the FDLIBM. Furthermore, the decimal number you got is extremely small, so unless you need it to 10^-16, then you might round to some precision and you'd get 0.

Thanks.

In the end the value (-1.2246467991473532E-16) did nothing when I updated the cars position.

double deltaX =  Math.cos(Math.toRadians(90-heading)) * car.getSpeed();
double deltaY = Math.sin(Math.toRadians(90-heading)) * car.getSpeed();

car.setLocation(car.getLocationX()+deltaX,car.getLocationY()+deltaY);

speed = 5, heading 270 (west)

car position (100,100) -> (95,100) no change in the Y posisiton so thats good

I hate programming games because Java is new to me (again) but C# to java is not that bad. :)

(no game clock yet just simple text output)

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.