Java:使用“Math.sin()”时可能会损失精度

1 java math trigonometry

我是 Java 新手。我想打印出每 15 度间隔的sin,costan值。

public class W3Aufgabe5 {
    public static void main(String[] args) {

        System.out.printf("%6s%6s%6s%6s%n", "Angle", "Sin", "Cos", "Tan");
        System.out.println("------------------------");

        for (float angle = 0; angle <= 180; angle += 15) {

            float sin = Math.sin(Math.toRadians(angle));
            float cos = Math.cos(Math.toRadians(angle));
            float tan = Math.tan(Math.toRadians(angle));

            System.out.printf("%6d%6d%6d%6d%n", angle, sin, cos, tan);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于每一Math.x()行,编译器打印

错误:可能
需要的精度损失:
找到浮点数:双 精度

我真的不明白。为什么double即使我一直在使用它也需要它float

rge*_*man 5

三角函数的方法sincostantoRadians所有接受double作为参数和返回double。没有接受floats 并返回floats 的重载。将 a 传递float给期望 a 的方法是合法的double;它将被隐式地扩大。但是当您将结果分配给s时,您不能double将 afloat隐式缩小为 a float

您可以显式转换的结果,float如果你想,但你得到更好的精度double,所以你的声明sincos以及tan变量double秒。

此外,格式说明符d表示整数值,而不是浮点值。使用格式说明符f而不是d. 您可能还希望在打印值时在值之间放置一些间距。