Check if a number is exactly representable as `f32`
The type Rational
from the rug
crate can represent fractions exactly. It also implements PartialEq<f32>
so you can compare the exact representation with your f32
directly to check if they are equal.
for n in 1u8..=255u8 {
let rat = Rational::from((n, 256));
let f = (n as f32) / 256.0;
println!("{}/256 -> {}", n, rat == f);
}
And as you can see from the output, the numbers you want to test are indeed exactly representable as f32
.
To get more a more interesting output, try 1 / n
:
for n in 1u8..=255u8 {
let rat = Rational::from((1, n));
let f = 1.0 / (n as f32);
println!("1/{} -> {}", n, rat == f);
}
This shows that only fractions with a power-of-2 denominator are exactly representable.