Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 1
Banker's rounding
Please tell me, are there any ways of classic rounding in Python 3?
10 Respostas
+ 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)
+ 2
Thank you, it was so easy
+ 2
Abhishek Sahoo, This is really useful and may come in handy, thank you :)
+ 1
You're welcome.
+ 1
Jianmin Chen ä½ å„½ļ¼can you please test your solution against test cases of 4.6 and 5.3?
+ 1
https://code.sololearn.com/ccPlRd5ZSdyj/?ref=app
Alisašøšø Please let me know if it's helpful
+ 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, ä½ å„½åļ¼ęä¼čÆ“äøęåč±ęćš
+ 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é£ę®µć
+ 1
Jianmin Chen yes it is correct banker's rounding now~ š
ē客ę°ļ½
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.