简体   繁体   English

Java中的精度损失

[英]Loss of precision in java

All integer literals are treated as int in java and floating point literals are treated as double in java. 在Java中,所有整数文字均被视为int,而在Java中,浮点文字则被视为double。 Then why does 那为什么

    byte b =10;

does not give any error but 没有给出任何错误,但是

   float f = 10.0;

gives a loss of precision error when in both cases down-casting takes place? 在两种情况下都进行向下转换时,会导致精度误差损失?

In the case of int to byte , there's no real concern about a loss of precision , because both types have the same degree of granularity. 对于intbyte的情况,不必担心精度损失,因为这两种类型的粒度相同。 You'll get an error if you try to convert a literal with a value outside the range of byte to byte . 如果尝试将值转换为bytebyte 范围之外的文字,则会出现错误。 (The error message given in that case is slightly misleading.) (在这种情况下给出的错误消息会引起误解。)

In the case of double to float , you can have a constant value which is in the right range , but still lose precision . 如果使用double float ,则可以有一个在正确范围内的常数值,但仍然会失去精度 In your specific case of 10.0, the value can be represented exactly in both float and double , but that's not the case in general. 在10.0的特定情况下,该值可以完全用floatdouble ,但通常情况并非如此。

As an example of that, consider this: 例如,考虑一下:

float f = (float) 10.1; // Or float f = 10.1f;
double d = 10.1;
System.out.println(f == d); // Prints false

That's because precision is being lost in the conversion from double to float - neither type can represent 10.1 exactly, but double gets close to it than float does. 这是因为在从doublefloat的转换中精度下降了-两种类型都不能精确表示10.1,但是doublefloat接近它。 The == operator will mean f is converted back to a double , with a different value to d . ==运算符将意味着f转换为double ,而d值不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM