How do I get the minimum or maximum value of an iterator containing floating point numbers?

Floats have their own min and max methods that handle NaN consistently, so you can fold over the iterator: use std::f64; fn main() { let x = [2.0, 1.0, -10.0, 5.0, f64::NAN]; let min = x.iter().fold(f64::INFINITY, |a, &b| a.min(b)); println!(“{}”, min); } Prints -10. If you want different NaN handling, you can use PartialOrd::partial_cmp. For … Read more

Why can’t I compare reals in Standard ML?

Why doesn’t 1.0 = 2.0 work? Isn’t real an equality type? No. The type variable ”Z indicates that the operands of = must have equality types. Why won’t reals in patterns work […]? Pattern matching relies implicitly on testing for equality. The cryptic error message syntax error: inserting EQUALOP indicates that the SML/NJ parser does … Read more

Does float have a negative zero? (-0f)

According to the standard, negative zero exists but it is equal to positive zero. For almost all purposes, the two behave the same way and many consider the existence of a negative to be an implementation detail. There are, however, some functions that behave quite differently, namely division and atan2: #include <math.h> #include <stdio.h> int … Read more

What is the difference between quiet NaN and signaling NaN?

When an operation results in a quiet NaN, there is no indication that anything is unusual until the program checks the result and sees a NaN. That is, computation continues without any signal from the floating point unit (FPU) or library if floating-point is implemented in software. A signalling NaN will produce a signal, usually … Read more

What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?

For a given IEEE-754 floating point number X, if 2^E <= abs(X) < 2^(E+1) then the distance from X to the next largest representable floating point number (epsilon) is: epsilon = 2^(E-52) % For a 64-bit float (double precision) epsilon = 2^(E-23) % For a 32-bit float (single precision) epsilon = 2^(E-10) % For a … Read more