Java:使用 `Math.sin()` 时可能会丢失精度
Java: Possible Loss of Precision When Using `Math.sin()`
我是 Java 的新手。我想每 15 度间隔打印出 sin
、cos
和 tan
值。
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);
}
}
}
对于每 Math.x()
行,编译器打印
error: possible loss of precision
required: float
found: double
我不是很明白。为什么它需要 double
,即使我一直在使用 float
?
三角函数sin
, cos
, tan
, and toRadians
都接受double
作为参数,returndouble
。没有接受 float
s 和 return float
s 的重载。将 float
传递给需要 double
的方法是合法的;它将被隐含地扩大。但是当您将结果分配给 float
s.
时,您不能隐式地将 double
缩小为 float
如果需要,您可以将结果显式转换为 float
,但使用 double
可以获得更好的精度,因此请声明您的 sin
、cos
和 tan
变量为 double
s.
此外,格式说明符 d
表示整数值,而不是浮点值。使用format specifier f
instead of d
。您可能还想在打印值时在值之间放置一些间距。
如果您查看 API documentation,您会发现所有触发方法都会 return 加倍。除非你真的需要一个浮动,否则你最好的选择是使用双打。您失去了精度,因为您必须将双 return 值强制为浮点数。
我是 Java 的新手。我想每 15 度间隔打印出 sin
、cos
和 tan
值。
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);
}
}
}
对于每 Math.x()
行,编译器打印
error: possible loss of precision
required: float
found: double
我不是很明白。为什么它需要 double
,即使我一直在使用 float
?
三角函数sin
, cos
, tan
, and toRadians
都接受double
作为参数,returndouble
。没有接受 float
s 和 return float
s 的重载。将 float
传递给需要 double
的方法是合法的;它将被隐含地扩大。但是当您将结果分配给 float
s.
double
缩小为 float
如果需要,您可以将结果显式转换为 float
,但使用 double
可以获得更好的精度,因此请声明您的 sin
、cos
和 tan
变量为 double
s.
此外,格式说明符 d
表示整数值,而不是浮点值。使用format specifier f
instead of d
。您可能还想在打印值时在值之间放置一些间距。
如果您查看 API documentation,您会发现所有触发方法都会 return 加倍。除非你真的需要一个浮动,否则你最好的选择是使用双打。您失去了精度,因为您必须将双 return 值强制为浮点数。