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

How do I use floating point number literals when using generic types?

Use the FromPrimitive trait: use num_traits::{cast::FromPrimitive, float::Float}; fn scale_float<T: Float + FromPrimitive>(x: T) -> T { x * T::from_f64(0.54).unwrap() } Or the standard library From / Into traits fn scale_float<T>(x: T) -> T where T: Float, f64: Into<T> { x * 0.54.into() } See also: How do I use number literals with the Integer trait … 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