如何解决java中的cos 90问题?
我在使用 Math.cos 函数计算 Java 中的余弦 90 时遇到一些问题:
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 的值,这是正确的。
我该怎么做才能使cos 90 = 0 的输出?所以,它使输出 x = 0 和 y = 4。
感谢您的建议
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你得到的很可能是非常非常小的数字,它们以指数表示法显示。您得到它们的原因是因为 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.
只需运行您的源代码,它就会返回:
这是绝对正确的。第一个值接近 0。第二个值如预期为 4。
3 * cos(90°) = 3 * 0 = 0
这里你必须阅读Math.toRadians() 文档说:
更新:您可以使用例如MathUtils.round() 来自 Apache Commons 存储库的方法,并将输出舍入为 8 位小数,如下所示:
这将为您提供:
Just run your source and it returns:
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:
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:
That will give you:
试试这个:
Try this: