Hypot Avoids Intermediate Overflow
Compare naive squaring with f64::hypot on huge and tiny inputs to show how hypot avoids intermediate overflow and underflow.
Code
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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.