Hypot Avoids Intermediate Overflow

Compare naive squaring with f64::hypot on huge and tiny inputs to show how hypot avoids intermediate overflow and underflow.

RustData Integrity

Code

rustsnippet
24 lines
fn main() {
    let x = 1.0e200_f64;
    let y = 1.0e200_f64;

    // squaring huge values overflows before the square root runs
    let naive = (x * x + y * y).sqrt();
    println!("naive: {naive}");

    // hypot scales the inputs so the intermediate value cannot overflow
    let stable = x.hypot(y);
    println!("hypot: {stable:e}");
    println!("finite: {}", stable.is_finite());

    // the same identity holds near the bottom of the floating-point range
    let tiny = 1.0e-200_f64;
    let naive_tiny = (tiny * tiny + tiny * tiny).sqrt();
    println!("tiny naive: {naive_tiny:e}");
    println!("tiny hypot: {:e}", tiny.hypot(tiny));

    // ordinary values agree with the Pythagorean identity
    let (a, b) = (3.0_f64, 4.0_f64);
    println!("3-4-5: {}", a.hypot(b));
    println!("squared: {}", a.hypot(b) * a.hypot(b));
}

How it works

One way to read it: the function main, doing all the work.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Putting it to use

Signature: fn main()

Expect labeled output — naive:, hypot:, finite: — when the file runs.

Core lines

let naive_tiny = (tiny * tiny + tiny * tiny).sqrt();
let naive = (x * x + y * y).sqrt();
let (a, b) = (3.0_f64, 4.0_f64);

Interactive Tools for This Topic

FAQ

What does Hypot Avoids Intermediate Overflow print when run?
Run it as a complete program — the output lines carry labels such as `naive:`, `hypot:`, `finite:`.