14

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

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

4 回答 4

19

使用精度格式说明符;a.后跟您希望查看的精度小数点数:

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,这f32这两个s中的小数点数都多。

pi is 3.14159274101257324218750000000000
k1 is 0.60725295543670654296875000000000

请注意,这些值不再匹配;浮点值很难!正如评论中提到的,您可能希望打印为 hexadecimal 甚至使用您的文字为 hexadecimal

于 2016-10-31T18:17:11.107 回答
6

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

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

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

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

游乐场示例

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

// 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
于 2018-12-05T21:24:25.067 回答
3

此答案是为 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
于 2014-10-26T19:51:22.917 回答
2

This answer was written for Rust 0.12.0 and doesn't apply to Rust 1.x.


You can use std::f32::to_string to print all the digits.

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

Output:

pi is 3.1415927410125732421875
k1 is 0.607252979278564453125
于 2014-10-26T20:00:04.350 回答