Skip to content

Instantly share code, notes, and snippets.

@AndrewRadev AndrewRadev/main.rs
Last active Nov 13, 2018

Embed
What would you like to do?
Divide successfully or default to zero
trait OrZero {
fn or_zero(self) -> Self;
}
impl OrZero for f64 {
fn or_zero(self) -> Self {
if self.is_normal() { self } else { 0.0 }
}
}
impl OrZero for f32 {
fn or_zero(self) -> Self {
if self.is_normal() { self } else { 0.0 }
}
}
fn main() {
let inf = 3.1 / 0.0;
let nan = 0.0 / 0.0;
println!("{:?} {:?}", inf, nan);
// inf NaN
let inf = (3.1 / 0.0).or_zero();
let nan = (0.0 / 0.0).or_zero();
println!("{:?} {:?}", inf, nan);
// 0.0 0.0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.