Square root of -1 = -1, bug or feature?

Square root of -1 = -1 ???

let root = -1_f64.sqrt();
println!("root: {}", root);

Should be NaN? Or better NarN not a real number :grinning:

fn main() {

    let mut num: f64 =1.0;
    let mut root = num.sqrt();
    println!("root: {}", root);
    
    num = -1.0;
    root = num.sqrt();
    println!("root: {}", root);
     
    root = 1_f64.sqrt();
    println!("root: {}", root);
     
    root = -1_f64.sqrt();
    println!("root: {}", root);
} 

output:

root: 1
root: NaN
root: 1
root: -1

Operator precedence! What you're doing is -(1_f64.sqrt()), not (-1_f64).sqrt()).

10 Likes

o.k. thank you

It should be noted that the square root of -0 is -0:

fn main() {
    let root = (-0_f64).sqrt();
    println!("root: {}", root);
}

Standard Error

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.39s
     Running `target/debug/playground`

Standard Output

root: -0

Rust Playground

That is presumably specified in IEEE-754. Floating point values can be weird, especially around signed zero.

5 Likes

With Mathematica it is 0

In[1]:= Sqrt[-1]
Sqrt[-0]

Out[1]= I

Out[2]= 0

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.