...

/

Puzzle 1: Explanation

Puzzle 1: Explanation

Let's find out how Rust handles floating-point precision.

Test it out

Hit “Run” to see the code’s output.

Press + to interact
fn main() {
const THREE_AND_A_BIT : f32 = 3.4028236;
println!("{}", THREE_AND_A_BIT);
}

Explanation

Most people expect the program to print 3.4028236. Surprisingly, the result is off by 0.0000001. The value is set at 3.4028236, yet the result is 3.4028237. This difference is how Rust represents 32-bit floating-point numbers (of the f32 type). Like many other languages, Rust represents floating-point numbers using the IEEE-754 standard, which defines the memory layout of a float as outlined below:

This standard also provides a formula to extract data from a floating-point variable in memory.

f32=sign(1 or 1)×2exponent127×1.mantissaf32 =sign (-1 \ or\ 1) \times 2^{exponent-127} \times 1.mantissa ...