3

I'm reading the Rust tutorial on rust-lang.org, and I came across the following code:

use std::f64;
fn angle(vector: (f64, f64)) -> f64 {
    let pi = f64::consts::PI;
    match vector {
      (0.0, y) if y < 0.0 => 1.5 * pi,
      (0.0, _) => 0.5 * pi,
      (x, y) => (y / x).atan()
    }
}

Normally for atan2 I would expect to see special cases for -0 and 0, for example to implement cases like these:

atan2(+0, +0) = +0
atan2(+0, −0) = +π
atan2(−0, +0) = −0
atan2(−0, −0) = −π

I'm not saying the tutorial should include those examples. After all it's just a demonstration of the match structure.

I'm just wondering if 0.0 would match -0.0 as well? Or if the two would be recognized as disjoint values?

1 Answer 1

5

Well, you can just try and test it! Here is a link to playtest: http://is.gd/NiS0gF

Apparently, 0.0 matches -0.0. This code:

fn main() {
    let x = -0.0f64;
    match x {
        0.0f64 => println!("Zero!"),
        _ => println!("Something else!")
    }
}

when run on playtest prints "Zero!", so 0.0 and -0.0 are the same thing from match perspective. And this is quite natural, provided that

fn main() {
    println!("{}", -0.0f64 == 0.0f64);
}

also prints "true".

Sign up to request clarification or add additional context in comments.

1 Comment

That makes sense, these kinds of comparisons are better done using specialized floating point functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.