如何解决java中的cos 90问题?

问题描述:

使用Math.cos函数在Java中计算余弦90时遇到一些问题:

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));

      }

}

当我计算cos90或cos270时,它给了我荒谬的值.它应该是0.我用91或271测试,给出了接近0的值,这是正确的.

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.

我应该怎么做才能使cos 90的输出= 0?因此,它使输出x = 0且y = 4.

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

感谢您的建议

您得到的很可能是非常非常小的数字,这些数字以指数表示法显示.之所以要使用它们,是因为pi/2在IEEE 754表示法中无法精确表示,因此无法获得90/270度的精确余弦.

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.