← 中文资源

简体中文版本

Hypot 避免中间溢出

用 f64::hypot 对比朴素的平方开方:在极大与极小输入下,hypot 避免中间结果溢出或下溢。

阅读英文原文

实现说明

Hypot 避免中间溢出可以归结为函数 main。

使用要点

  • 跑完文件,输出里会留下标记——naive:、hypot:、finite:。

常见问题

运行「Hypot 避免中间溢出」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 naive:、hypot:、finite: 标签标明各步骤。

核心语句

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

代码示例

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));
}