Kotlin 1.8 will have a new `..<`/`rangeUntil` operator which returns a
OpenEndRange
, with support for floats
ephemient
11/29/2022, 2:02 AM
I suppose you could do something like
Copy code
infix fun Float.until(to: Float): ClosedFloatingPointRange<Float> = this .. when {
to < 0f -> Float.fromBits(to.toBits() + 1)
to > 0f -> Float.fromBits(to.toBits() - 1)
to == 0f -> -Float.MIN_VALUE
else -> to
}
in current/earlier Kotlin versions to produce the nearest closed range that contains everything the open range would
ephemient
11/29/2022, 2:09 AM
(basically mirroring how Kotlin translates
0 until 3
into
0..2
on integers currently, except that we have to do a bit of bit manipulation to get the immediately prior floating point value)
m
Michael Paus
11/29/2022, 11:37 AM
You could have also used the floating point
ulp
function here but I guess the bit fiddling may be even more efficient.
e
ephemient
11/29/2022, 4:42 PM
ulp
is the delta to the successor, not the prior, which is not necessarily the same
ephemient
11/29/2022, 4:45 PM
e.g.
Copy code
val x = 1f
val y = x - x.ulp
val z = Float.fromBits(1f.toBits() - 1)
y < z && z < x
so you can't actually use it to decrement the range end