Dav*_*ing 12 java math trigonometry
我在使用Math.cos函数计算Java中的cosinus 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));
}
Run Code Online (Sandbox Code Playgroud)
}
当我计算cos90或cos270时,它给出了我的自动值.它应该是0.我用91或271测试,给出接近0是正确的.
我应该怎么做cos 90 = 0的输出?所以,它使输出x = 0和y = 4.
感谢您的建议
只需运行您的源代码,它就会返回:
cos 90 : 1.8369701987210297E-16
sin 90 : 4.0
Run Code Online (Sandbox Code Playgroud)
那是绝对正确的.第一个值接近0.第二个值是预期的4.
3 * cos(90°) = 3 * 0 = 0
在这里,您必须阅读Math.toRadians() 文档,其中说:
将以度为单位的角度转换为以弧度为单位测量的近似等效角度.从度到弧度的转换通常是不精确的.
更新:您可以使用Apache Commons存储库中的MathUtils.round()方法,并将输出四舍五入为8位小数,如下所示:
System.out.println("cos 90 : " + MathUtils.round(x, 8));
Run Code Online (Sandbox Code Playgroud)
那会给你:
cos 90 : 0.0
sin 90 : 4.0
Run Code Online (Sandbox Code Playgroud)