Why 20.5_f64.round() do not eq with np.round(20.5)?

hey, i am trying to translate my python code to rust,
but feel confused with the rust...

why ?

# python 
round(20.5)  ===> 20 
np.round(20.5) ===> 20 
np.around(20.5) ===> 20 

but rust got

20.5_f64.round() ===> 21

could anyone tell me the reason?

The documentation is clear: in Rust, f64::round() rounds away from 0. In contrast, NumPy uses banker's rounding (rounds ties to even).


different language use different strategy to solve this,
it make me sad. i have to write extra code to process this.

That’s because round method in Rust is actual rounding - ceiling if >= x.5 and flooring if < x.5.

python use banker rounding, and the same name gave me misleading....

See also:


There's no single "actual" rounding, mind. The one you describe is just one of many rounding modes; the banker's rounding used by Python is just as "actual". The IEEE-754 standard supports both "ties away from zero" and "ties to even" – the former causes a slight bias that the latter fixes, which is why it's used in banking.


Not sure it's actually used in banking. At least the IRS says to always round 0.50 up in tax forms for some reason :slight_smile:

I am super-surprised f64::round doesn't round to even, given that all other f64 operations, and Display, round to even.


I suppose we inherited that choice from C and C++.

only python3 and .Net use bank rounding .
i don't understand why python3 use bank rounding as standard, why not provide another way to impl it.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.