简体   繁体   English

像 `f64::from_str` 一样准确地计算 `n * 10^p`?

[英]Compute `n * 10^p` as accurately as `f64::from_str` does?

I've got two values: n: f64 and p: i32 , and I need to compute n * 10^p .我有两个值: n: f64p: i32 ,我需要计算n * 10^p

I tried two methods:我尝试了两种方法:

  1. Using multiplication and f64::powi使用乘法和f64::powi
  2. Using format!() and f64::from_str使用format!()f64::from_str

The latter is more accurate (see output below) but obviously inefficient.后者更准确(参见下面的 output)但显然效率低下。 Is there a way to get the same accuracy without going through a string conversion?有没有办法在不经过字符串转换的情况下获得相同的准确性? Here's my code:这是我的代码:

fn main() {
    let f1 = |n: f64, e: i32| n * 10f64.powi(e);
    let f2 = |n: f64, e: i32| format!("{}e{}", n, e).parse::<f64>().unwrap();
    for &n in &[1.1, 2.2, 3.3, 4.4] {
        for &e in &[-2, 2] {
            println!("{} {}", f1(n, e), f2(n, e));
        }
    }
}

Output: Output:

0.011000000000000001 0.011
110.00000000000001 110
0.022000000000000002 0.022
220.00000000000003 220
0.033 0.033
330 330
0.044000000000000004 0.044
440.00000000000006 440

Playground 操场

As always, there is a crate for it: rust_decimal It is not exactly, what you want, but it adds the needed precision to your task without going the way of formatting.与往常一样,它有一个板条箱: rust_decimal它不完全是您想要的,但它为您的任务增加了所需的精度,而无需进行格式化。 Maybe give it a try, it is unfortunately not possible to use it on the playground.也许试一试,不幸的是不能在操场上使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM