Skip to content

Add Integer.nearestFloat, and make Integer.float a bit more useful #759

@ePaul

Description

@ePaul

Summary

  • Make Integer.float more liberal, allowing conversions whenever they are exact.
  • Introduce an Integer.nearestFloat to 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions