how to solve cos 90 problem in java? [duplicate]

人盡茶涼 提交于 2019-11-30 22:45:55

问题


I have some problems with calculating cosinus 90 in Java using Math.cos function :

public class calc{
      private double x;
      private double y;

      public calc(double x,double y){
                   this.x=x;
                   this.y=y;
      }

      public void print(double theta){
           x = x*Math.cos(theta);
           y = y*Math.sin(theta);
           System.out.println("cos 90 : "+x);
           System.out.println("sin 90 : "+y);
      }

      public static void main(String[]args){
           calc p = new calc(3,4);
           p.print(Math.toRadians(90));

      }

}

When I calculate cos90 or cos270, it gives me absurb values. It should be 0. I tested with 91 or 271, gives a near 0 which is correct.

what should I do to make the output of cos 90 = 0? so, it makes the output x = 0 and y = 4.

Thankful for advice


回答1:


What you're getting is most likely very, very small numbers, which are being displayed in exponential notation. The reason you're getting them is because pi/2 is not exactly representable in IEEE 754 notation, so there's no way to get the exact cosine of 90/270 degrees.




回答2:


Just run your source and it returns:

cos 90 : 1.8369701987210297E-16
sin 90 : 4.0

That's absolutely correct. The first value is nearly 0. The second is 4 as expected.

3 * cos(90°) = 3 * 0 = 0

Here you have to read the Math.toRadians() documentation which says:

Converts an angle measured in degrees to an approximately equivalent angle measured in radians. The conversion from degrees to radians is generally inexact.

Update: You can use for example the MathUtils.round() method from the Apache Commons repository and round the output to say 8 decimals, like this:

System.out.println("cos 90 : " + MathUtils.round(x, 8));

That will give you:

cos 90 : 0.0
sin 90 : 4.0



回答3:


Try this:

public class calc
{
    private double x;
    private double y;
    public calc(double x,double y)
    {
        this.x=x;
        this.y=y;
    }
    public void print(double theta)
    {
        if( ((Math.toDegrees(theta) / 90) % 2) == 1)
        {
            x = x*0;
            y = y*Math.sin(theta);
        }
        else if( ((Math.toDegrees(theta) / 90) % 2) == 0)
        {
            x = x*Math.cos(theta);
            y = y*0; 
        }
        else
        {
           x = x*Math.cos(theta);
           y = y*Math.sin(theta); 
        }
        System.out.println("cos 90 : "+x);
        System.out.println("sin 90 : "+y);
    }
    public static void main(String[]args)
    {
        calc p = new calc(3,4);
        p.print(Math.toRadians(90));
    }
}


来源:https://stackoverflow.com/questions/5263653/how-to-solve-cos-90-problem-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!