Skip to content

Instantly share code, notes, and snippets.

@hariedo
Created March 29, 2024 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hariedo/ad6a8c1cab8d7d0aef25de7068c9a396 to your computer and use it in GitHub Desktop.
Save hariedo/ad6a8c1cab8d7d0aef25de7068c9a396 to your computer and use it in GitHub Desktop.
// 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);
}
@hariedo
Copy link
Author

hariedo commented Mar 29, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment