Domanda

A.) Does precision loss happens when one converts a float to a double in Java ?

B.) If I typecast a float to a float does that result in any precision loss or does Java simply intelligently ignores/skips such kind of typecasting ?

È stato utile?

Soluzione

Question A is covered by the Java Language Specification, Widening Primitive Conversion.

"Conversions widening from float to double in strictfp expressions also preserve the numeric value exactly; however, such conversions that are not strictfp may lose information about the overall magnitude of the converted value."

The non-strictfp issue relates to numbers with extreme exponent values. The issue is discussed in FP-strict Expressions.

"Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow."

If you want to be sure that conversions from float to double will be exact, use strictfp.

Question B is a question about Identity Conversions. I'm not sure whether an identity conversion can trigger a change in value set, involving the same strictfp vs. non-strict issue as for Question A.

Altri suggerimenti

Assume a double is a 64-bit bucket and a float a 32-bit bucket. If you empty the contents of a float into the double-bucket surely it will fit with more space to spare. However converting from double to float won't be the same because the float-bucket is just too small to hold the bigger content of a double. In case of float to float, they are all of the same size so you surely won't lose nothing and will fit perfectly into each other's buckets.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top