如何以所有可用精度打印Rust浮点数?

问题描述 投票:9回答:4

我正在为sin三角函数实现CORDIC算法。为了做到这一点,我需要硬编码/计算一堆反正切值。现在我的函数似乎可以工作(由Wolfram Alpha验证)到打印的精度,但我希望能够打印我的f32的所有32位精度。我该怎么办?

fn generate_table() {
    let pi: f32 = 3.1415926536897932384626;
    let k1: f32 = 0.6072529350088812561694; // 1/k
    let num_bits: uint = 32;
    let num_elms: uint = num_bits;
    let mul: uint = 1 << (num_bits - 2);

    println!("Cordic sin in rust");
    println!("num bits {}", num_bits);
    println!("pi is {}", pi);
    println!("k1 is {}", k1);

    let shift: f32 = 2.0;
    for ii in range(0, num_bits) {
        let ipow: f32 = 1.0 / shift.powi(ii as i32);
        let cur: f32 = ipow.atan();
        println!("table values {}", cur);
    }
}
formatting rust cordic
4个回答
10
投票

使用precision format specifier;一个.后跟你想看的精度小数点:

fn main() {
    let pi: f32 = 3.1415926536897932384626;
    let k1: f32 = 0.6072529350088812561694; // 1/k

    println!("pi is {:.32}", pi);
    println!("k1 is {:.32}", k1);
}

我选择了32,这超过了这些f32s中的小数点数。

pi is 3.14159274101257324218750000000000
k1 is 0.60725295543670654296875000000000

请注意,值不再匹配; floating point values are difficult!如评论中所述,您可能希望print as hexadecimal or even use your literals as hexadecimal


2
投票

这个答案是为Rust 0.12.0编写的,不适用于Rust 1.x.


你可以在to_string中使用std::f32函数(不要与to_string方法混淆):

fn main() {
    println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(1) }));
    println!("{}", std::f32::to_string(unsafe { std::mem::transmute::<i32, f32>(16) }));
    println!("{}", std::f32::to_string(std::f32::MIN_POS_VALUE));
    println!("{}", std::f32::to_string(std::f32::MAX_VALUE));
    println!("{}", std::f32::to_string(std::f32::consts::PI));
}

输出:

0.00000000000000000000000000000000000000000000140129852294921875
0.000000000000000000000000000000000000000000022420775890350341796875
0.000000000000000000000000000000000000011754944324493408203125
340282368002860660002286082464244022240
3.1415927410125732421875

2
投票

这个答案是为Rust 0.12.0编写的,不适用于Rust 1.x.


您可以使用std::f32::to_string打印所有数字。

use std::f32;

fn main() {
    let pi: f32 = 3.1415926536897932384626;
    let k1: f32 = 0.6072529350088812561694; // 1/k

    println!("pi is {}", f32::to_string(pi));
    println!("k1 is {}", f32::to_string(k1));
}

输出:

pi is 3.1415927410125732421875
k1 is 0.607252979278564453125

2
投票

使用精度格式说明符是正确的答案,但要打印所有可用的精度,只需避免指定要显示的位数:

// prints 1
println!("{:.}", 1_f64);

// prints 0.000000000000000000000000123
println!("{:.}", 0.000000000000000000000000123_f64); 

这样,您不会截断值,也不会修剪多余的零,并且显示对于所有值都是正确的,无论它们是非常大还是非常小。

Playground example

为了完整性,精度格式说明符还支持指定固定精度(根据接受的答案):

// prints 1.0000
println!("{:.4}", 1_f64);

以及在运行时指定的精度(当然不需要是const):

// prints 1.00
const PRECISION: usize = 2;
println!("{:.*}", PRECISION, 1_f64); // precision specifier immediately precedes positional argument
© www.soinside.com 2019 - 2024. All rights reserved.