0

This code:

let average = |a: f32, b: f32, c: f32| {
    (a + b + c) / 3.0
};

println!("With function: {}", average(11.0, -22.0, 33.0));
println!("Without function: {}", (11.0 - 22.0 + 33.0) / 3.0);

prints this result:

With function: 7.3333335
Without function: 7.333333333333333

Why are they different?

kmdreko
  • 42,554
  • 6
  • 57
  • 106
CocDap
  • 180
  • 4

1 Answers1

4

The discrepancy comes from using different types to evaluate the same mathematical expression. The closure uses f32s (as annotated) while the version without it uses f64s. The type of numeric literals with decimals defaults to f64 unless inferred or suffixed otherwise.

So the latter has twice the precision. If the closure were annotated with f64s instead, you would get the same result:

let average = |a: f64, b: f64, c: f64| {
    (a + b + c) / 3.0
};

println!("With function: {}", average(11.0, -22.0, 33.0));
println!("Without function: {}", (11.0 - 22.0 + 33.0) / 3.0);
With function: 7.333333333333333
Without function: 7.333333333333333
kmdreko
  • 42,554
  • 6
  • 57
  • 106