The discrepancy comes from using different types to evaluate the same mathematical expression. The closure uses f32
s (as annotated) while the version without it uses f64
s. 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 f64
s 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