Created
March 29, 2024 15:51
-
-
Save hariedo/ad6a8c1cab8d7d0aef25de7068c9a396 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a float f, return next possible representation. | |
// This method will have issues around +/-maxfloat, +/-infinity, NaN. | |
// | |
public static float NextULP(float f, int ulp=1) | |
{ | |
int bits = System.BitConverter.SingleToInt32Bits(f); | |
return System.BitConverter.Int32BitsToSingle(bits + ulp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ULP - Unit of Least Precision.
Floating point numbers with limited bits cannot express all possible values. The delta between possible values varies as the distance from zero increases. In IEEE754, neighboring float values are consecutive binary values because the mantissa is stored in the lowest significant bits and the exponent is immediately the next more significant bits (so overflow of the mantissa immediately affects the exponent correctly).
Shout out to https://www.h-schmidt.net/FloatConverter/IEEE754.html to visualize things like this.