Created
July 11, 2020 15:30
-
-
Save Techcable/809b1803790d9ce01a5d860db5f01400 to your computer and use it in GitHub Desktop.
Floating Point Raw ULP comparison
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
//! Taken from Stack overflow: ttps://stackoverflow.com/a/17871376/5713037 | |
fn diff_ulps(a: f64, b: f64) -> u64 { | |
(raw_ulps(a) as i64).wrapping_sub(raw_ulps(b) as i64).abs() as u64 | |
} | |
fn raw_ulps(f: f64) -> u64 { | |
assert!(!f.is_nan()); | |
let b: u64 = f.to_bits(); | |
const TOP: u64 = 0x8000_0000_0000_0000; | |
let b = if (b as i64) < 0 { TOP.wrapping_sub(b) } else { b }; | |
assert!((b as i64) >= 0); | |
b | |
} | |
// original: | |
/* | |
public static boolean compareDoubleEquals(double expected, double actual, long maxUlps) { | |
long expectedBits = Double.doubleToLongBits(expected) < 0 ? 0x8000000000000000L - Double.doubleToLongBits(expected) : Double.doubleToLongBits(expected); | |
long actualBits = Double.doubleToLongBits(actual) < 0 ? 0x8000000000000000L - Double.doubleToLongBits(actual) : Double.doubleToLongBits(actual); | |
long difference = expectedBits > actualBits ? expectedBits - actualBits : actualBits - expectedBits; | |
return !Double.isNaN(expected) && !Double.isNaN(actual) && difference <= maxUlps; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment