如何使用Rust在运行时识别浮点精度?

时间:2018-05-16 03:29:14

标签: rust

如何识别下面代码(enter image description here)中1.0005的精度在运行时是4?:

fn round(n: f64, precision: u32) -> f64 {
    (n * 10_u32.pow(precision) as f64).round() / 10_i32.pow(precision) as f64
}

fn main() {
    let x = 1.0005_f64;

    println!("{:?}", round(x, 1));
    println!("{:?}", round(x, 2));
    println!("{:?}", round(x, 3));
    println!("{:?}", round(x, 4));
    println!("{:?}", round(x, 5));
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否正确理解了这个问题。你想要小数位数?

fn round(n: f64, precision: u32) -> f64 {
    (n * 10_u32.pow(precision) as f64).round() / 10_i32.pow(precision) as f64
}

fn precision(x: f64) -> Option<u32> {
    for digits in 0..std::f64::DIGITS {
        if round(x, digits) == x {
            return Some(digits);
        }
    }
    None
}

fn main() {
    let x = 1.0005_f64;

    println!("{:?}", precision(x));
}

Playground

我还建议让你的圆形功能中的类型更大一些,这样你就不会那么快地遇到溢出。上述代码已失败为x = 1e-10

fn round(n: f64, precision: u32) -> f64 {
    let precision = precision as f64;
    (n * 10_f64.powf(precision)).round() / 10_f64.powf(precision)
}