Reputation: 7867
On one hand, Math.random() or new Random().nextFloat() should return value between 0 and 1 but not include 1, on the other hand float number may be inaccurate that the value may vary around the actual value. Does it imply that Math.random() or new Random().nextFloat() may return a value <0 or >=1 in practical? If not, why would that not happen?
Upvotes: 1
Views: 108
Reputation: 280973
No. The documentation specifically guarantees the range of possible outputs, and it specifies an algorithm that the implementation must be equivalent to:
public float nextFloat() {
return next(24) / ((float)(1 << 24));
}
which is guaranteed to produce a result in the half-open interval [0.0, 1.0).
While floating-point operations inherently must round their results, the basic operations like /
or conversion to floating-point have specific, standardized rounding behavior. In this case, the result of every floating-point operation involved is exactly representable, so no rounding error is incurred.
Upvotes: 5
Reputation: 7344
According of how IEEE754 works, you are safe because if you want to encode the number 1.0 you will have:
exponent - mantissa
011111111 - 00000...00
randomize the mantissa and the last 7 bits of the exponent (and not letting them all be 1 at the same time), you will always have a number between 0 and 1.
You also won't have a negative number because you must set explicitly the sign bit to make it negative.
Upvotes: -1