Amir
Amir

Reputation: 898

How to round up or down when converting f32 to bf16 in rust?

I am converting from f32 to bf16 in rust, and want to control the direction of the rounding error. Is there an easy way to do this?

Converting using the standard bf16::to_f32 rounds to the nearest bf16 value, which can be either larger or smaller than the original:

use half::bf16;
fn main() {
    for x in vec![0.1_f32, 0.11, 0.12] {
        let xh = bf16::from_f32(x);
        let diff = x - bf16::to_f32(xh);
        println!("{}, {}, {}",  x, bf16::from_f32(x), diff)
    }
}

Output:

0.1, 0.100097656, -0.00009765476
0.11, 0.10986328, 0.00013671815
0.12, 0.12011719, -0.00011719018

Upvotes: 1

Views: 237

Answers (0)

Related Questions