Last active
November 13, 2018 10:23
-
-
Save AndrewRadev/59098b853ec13f350a07038d7653a18e to your computer and use it in GitHub Desktop.
Divide successfully or default to zero
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
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