-
Notifications
You must be signed in to change notification settings - Fork 46
Description
Summary
- Make
Integer.floatmore liberal, allowing conversions whenever they are exact. - Introduce an
Integer.nearestFloatto allow lossy conversions to Float.
Details
During the review of #756, we noted that Integer's float attribute throws an exception whenever the value is ±2^53 or beyond. The reason for this is that Float (and Java's double) have only 53 bits of mantissa, so larger Integer values can not always be represented exactly as a Float.
But some of those values actually can be represented exactly, namely those which are a multiple of a suitable power of two so the other factor fits into 53 bits. These are exactly those values which also can result from Float.integer (for Floats in the range [-2^(-63)..(2^63-2^10)] or something similar).
Those Integers can be checked in Java by value == (long)(double)value, or in Ceylon by int.nearestFloat.integer == int with the nearestFloat attribute discussed below. (I didn't use int.float.integer == int, because we are just talking about the implementation of float.)
Thus I propose to extend the definition of Integer.float to only throw an exception in those cases where the Integer value is not representable exactly as a Float value.
In other cases we might not need an exact conversion to Float, but just some Float nearby (ideally the nearest one). An example is Ceylon-SDK issue #296.
This currently can be emulated using the fact that the arithmetic operators do an automatic promotion from Integer to Float: int + 0.0 (or int * 1.0) gives the nearest Float value to int.
I propose to make this more explicit by adding a nearestFloat attribute to the Integer class, returning the nearest float to the integer value, and never throwing an OverflowException. That might be implemented in Ceylon as above (arithmetically), or in Java as a simple cast to double: (double)value.