+ 1

Banker's rounding

Please tell me, are there any ways of classic rounding in Python 3?

1st Jan 2020, 10:22 PM
Alisa🌸🌸
Alisa🌸🌸 - avatar
10 Antworten
+ 1
Oh sorry, Aymane Boukrouh. My mistake. Alisa🌸🌸, there are no built-in functions to do what you're talking about, but you can create a custom function: import math def bankers_rounding(num): if math.floor(num) % 2 == 0: #if rounding down num returns an even number return math.floor(num) else: return math.ceil(num)
1st Jan 2020, 10:46 PM
Jianmin Chen
Jianmin Chen - avatar
+ 2
Thank you, it was so easy
1st Jan 2020, 10:50 PM
Alisa🌸🌸
Alisa🌸🌸 - avatar
+ 2
Abhishek Sahoo, This is really useful and may come in handy, thank you :)
3rd Jan 2020, 4:28 PM
Alisa🌸🌸
Alisa🌸🌸 - avatar
+ 1
You're welcome.
1st Jan 2020, 10:50 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
Jianmin Chen 你好,can you please test your solution against test cases of 4.6 and 5.3?
2nd Jan 2020, 5:40 AM
Gordon
Gordon - avatar
3rd Jan 2020, 1:50 PM
ABHISHEK
ABHISHEK - avatar
+ 1
Gordon , I'm pretty sure the program works correctly for those two numbers. 4.6 will return 4, and 5.3 will return 6. By the way, 你好吗?我会说中文和英文。😃
3rd Jan 2020, 7:27 PM
Jianmin Chen
Jianmin Chen - avatar
+ 1
Jianmin Chen 我也會中文呀 banker's rounding 的話,4.6還是應該進位為5,5.3還是應該捨棄為5。只有.5時才要找最接近雙數,來平衡多次加減的誤差bias。 見: https://en.m.wikipedia.org/wiki/Rounding 引用一: Round half to even Edit A tie-breaking rule without positive/negative bias and without bias toward/away from zero is round half to even. By this convention, if the fractional part of x is 0.5, then y is the even integer nearest to x. Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5. This function minimizes the expected error when summing over rounded figures, even when the inputs are mostly positive or mostly negative. This variant of the round-to-nearest method is also called convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd–even rounding,[6] or bankers' rounding. 解決的問題,見 Vancouver Stock Exchange那段。
4th Jan 2020, 2:28 AM
Gordon
Gordon - avatar
+ 1
Jianmin Chen yes it is correct banker's rounding now~ 👏 甭客气~
4th Jan 2020, 3:10 AM
Gordon
Gordon - avatar
0
Gordon, I see my error! Thanks for informing me, I wouldn't have known. So, Alisa🌸🌸, this means the correct code is: import math def bankers_rounding(num): if (num - 0.5).is_integer() and (num + 0.5).is_integer(): #if number is exactly between two whole numbers if math.floor(num) % 2 == 0: #if rounding down returns an even number return math.floor(num) else: return math.ceil(num) else: return round(num) #if not exactly between two whole numbers, return the normally rounded amount I believe that's my mistake, right? The number had to be exactly between two whole numbers in order to be rounded in the bankers' rounding method. 谢谢, Gordon.
4th Jan 2020, 2:56 AM
Jianmin Chen
Jianmin Chen - avatar