Message375746
thank you very much about the hints, i've improved the code as follows.
def rnd(x, n=0):
a = x*10**(n + 1)
b = int(a)
if abs(a - b) >= 0.5: b += 1 if x >= 0 else -1
a = b/10
b = int(a)
if abs(a - b) >= 0.5: b += 1 if x >= 0 else -1
return b/10**n
def rndup(x, n=0):
a = x*10**(n + 1)
b = int(a)
if abs(a - b) > 0: b += 1 if x >= 0 else -1
a = b/10
b = int(a)
if abs(a - b) > 0: b += 1 if x >= 0 else -1
return b/10**n
now it manage well your cases ...
print(rnd(2.8 - 1.3), 2.8 - 1.3)
print(rnd(1.8 - 1.3), 1.8 - 1.3)
print(rnd(-2.8 + 1.3), -2.8 + 1.3)
print(rnd(-1.8 + 1.3), -1.8 + 1.3)
results ...
2.0 1.4999999999999998
1.0 0.5
-2.0 -1.4999999999999998
-1.0 -0.5
we have to define limits caused by the floating point internal representation but for general use in my opinion can work fine. do you see other cases where it cracks? |
|
Date |
User |
Action |
Args |
2020-08-21 08:02:28 | marco_ocram | set | recipients:
+ marco_ocram, rhettinger, ronaldoussoren, mark.dickinson, stutzbach, veky |
2020-08-21 08:02:28 | marco_ocram | set | messageid: <1597996948.14.0.70028770611.issue41598@roundup.psfhosted.org> |
2020-08-21 08:02:28 | marco_ocram | link | issue41598 messages |
2020-08-21 08:02:28 | marco_ocram | create | |
|