首先,我想指出的是,这个问题不是重复的:
我知道IEEE 754,我知道:The simple "always round 0.5 up" technique results in a slight bias toward the higher number. With large numbers of calculations, this can be significant. The Python 3.0 approach eliminates this issue.
我同意ROUND_HALF-UP方法不如Python中默认实现的方法。然而,也有人不知道这一点,如果规范要求的话,就需要使用这种方法。简单的方法是:def round_my(num, precission):
exp = 2*10**(-precission)
temp = num * exp
if temp%2 < 1:
return int(temp - temp%2)/exp
else:
return int(temp - temp%2 + 2)/exp
但我认为这不是Python。。。根据docs我应该使用类似于:
^{pr2}$
问题是这并不能通过所有的测试用例:class myRound(unittest.TestCase):
def test_1(self):
self.assertEqual(piotrSQL.round_my(1.53, -1), 1.5)
self.assertEqual(piotrSQL.round_my(1.55, -1), 1.6)
self.assertEqual(piotrSQL.round_my(1.63, -1), 1.6)
self.assertEqual(piotrSQL.round_my(1.65, -1), 1.7)
self.assertEqual(piotrSQL.round_my(1.53, -2), 1.53)
self.assertEqual(piotrSQL.round_my(1.53, -3), 1.53)
self.assertEqual(piotrSQL.round_my(1.53, 0), 2)
self.assertEqual(piotrSQL.round_my(1.53, 1), 0)
self.assertEqual(piotrSQL.round_my(15.3, 1), 20)
self.assertEqual(piotrSQL.round_my(157.3, 2), 200)
因为浮点数和十进制数之间的转换性质,而且量子化对于指数10或100似乎不起作用。有没有Python式的方法可以做到这一点?在
我知道我可以加上无穷小的数,round(num+10**(precission-20),-pricission)就可以了,但这是错误的,以至于“小狗会死”。。。在