Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

floating point - How quickly check whether double fits in float? (Java)

Are there some arithmetic or bitwise operations that can check whether a double fits into a float without loss of precision.

It should not only check that the double range is in the float range, but also that no mantissa bits get lost.

Bye

P.S.: This answers the problem half way for C#: How to check if a double can fit into a float without conversion to infinity But I need a solution that works for Java.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about this:

double d = ...;
if ((double)(float)d == d) {
   System.out.println(d + " fits into float!");
}

The idea is pretty simple: We first cast to float and then back to double and check whether the result is still the same. If d does not fit into float, then some precision would have been lost at the (float)d cast and thus the result would be different.

Strictly speaking, the cast back to double is not necessary as the comparision operator will do this cast implicitly, so (float)d == d is also fine.

If you are worried about the performance of this, because many float operations are a lot slower than comparable int operations: This is pretty much a non-issue here. Conversion between float and double is extremely efficient in modern CPUs. It can even be vectorized! There are the cvtpd2ps and cvtps2pd instructions in the SSE2 instruction set that perform the conversion from double to float and vice versa (4 values are converted at once). The instructions have a latency of 4 cycles on all Intel CPUs that support them. 4 cycles for 4 conversions is extremely fast.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...