-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix: NextFloat/Double could return a value equal to max due to floati…
…ng point error
- Loading branch information
1 parent
511889a
commit d71d0ab
Showing
2 changed files
with
84 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
namespace RandomExtensions; | ||
|
||
internal static class MathEx | ||
{ | ||
#if !NET6_0_OR_GREATER | ||
public static double BitDecrement(double x) | ||
{ | ||
long bits = BitConverter.DoubleToInt64Bits(x); | ||
|
||
if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000) | ||
{ | ||
// NaN returns NaN | ||
// -Infinity returns -Infinity | ||
// +Infinity returns double.MaxValue | ||
return (bits == 0x7FF00000_00000000) ? double.MaxValue : x; | ||
} | ||
|
||
if (bits == 0x00000000_00000000) | ||
{ | ||
// +0.0 returns -double.Epsilon | ||
return -double.Epsilon; | ||
} | ||
|
||
// Negative values need to be incremented | ||
// Positive values need to be decremented | ||
|
||
bits += ((bits < 0) ? +1 : -1); | ||
return BitConverter.Int64BitsToDouble(bits); | ||
} | ||
|
||
public static float BitDecrement(float x) | ||
{ | ||
int bits = BitConverter.SingleToInt32Bits(x); | ||
|
||
if ((bits & 0x7F800000) >= 0x7F800000) | ||
{ | ||
// NaN returns NaN | ||
// -Infinity returns -Infinity | ||
// +Infinity returns float.MaxValue | ||
return (bits == 0x7F800000) ? float.MaxValue : x; | ||
} | ||
|
||
if (bits == 0x00000000) | ||
{ | ||
// +0.0 returns -float.Epsilon | ||
return -float.Epsilon; | ||
} | ||
|
||
// Negative values need to be incremented | ||
// Positive values need to be decremented | ||
|
||
bits += ((bits < 0) ? +1 : -1); | ||
return BitConverter.Int32BitsToSingle(bits); | ||
} | ||
|
||
#endif | ||
} |