如何以所有可用的精度打印Rust浮点数? [英] How do I print a Rust floating-point number with all available precision?

查看:434
本文介绍了如何以所有可用的精度打印Rust浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am implementing the CORDIC algorithm for the sin trigonometric function. In order to do this, I need to hardcode/calculate a bunch of arctangent values. Right now my function seems to work (as validated by Wolfram Alpha) to the precision that is printed, but I would like to be able to print all 32 bits of precision of my f32. How may I do that?

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

推荐答案

使用

Use the precision format specifier; a . followed by the number of decimal points of precision you'd like to see:

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中的小数点位数更多.

I chose 32, which is more than the number of decimal points in either of these f32s.

pi is 3.14159274101257324218750000000000
k1 is 0.60725295543670654296875000000000

请注意,这些值不再匹配; 浮点值很困难!如评论中所述,您可能希望以十六进制打印,甚至可以使用文字作为十六进制.

Note that the values no longer match up; floating point values are difficult! As mentioned in a comment, you may wish to print as hexadecimal or even use your literals as hexadecimal.

这篇关于如何以所有可用的精度打印Rust浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆