开发者

Python rounding problem

开发者 https://www.devze.com 2022-12-31 09:31 出处:网络
>>> num = 4.123456 >>> round(num, 3) # expecting 4.123 4.1230000000000002 开发者_如何学C
>>> num = 4.123456
>>> round(num, 3) # expecting 4.123
4.1230000000000002
开发者_如何学C

I'm expecting 4.123 as a result, Am I wrong?


This is not a mistake. You need to read What Every computer Scientist Should Know About Floating Point Arithmetic:

http://docs.sun.com/source/806-3568/ncg_goldberg.html


Yep, your expectations don't match the design intent of your tools.

Check out this section of the Python tutorial.


Using math.round is actually pretty rare. if you're trying to display a number as a string to a certain precision, you might want something more like

>>> num = 4.123456
>>> print "%.3f" % num
4.123

You might be interested in the documentation on string formatting.


Why do you care? (That's a serious question.)

The answer that you're getting is so close to 4.123 as to make no difference. It can't be exactly 4.123, since there are only finitely many numbers (around 2**64 on a typical machine) that Python can represent exactly, and without going into detail about floating-point representations, it just so happens that 4.123 isn't one of those numbers. By the way, 4.1230000000000002 isn't one of the numbers that can be exactly represented, either; the actual number stored is 4.12300000000000022026824808563105762004852294921875, but Python truncates the decimal representation to 17 significant digits for display purposes. So:

  1. If you're doing mathematics with the result, then the difference between 4.123 and what you're getting is so tiny as to make no real difference. Just don't worry about it.
  2. If you just care about the output looking pretty (i.e., what you're after here is a string rather than a number) then use str, or string formatting.
  3. In the unlikely case that the difference really does matter, e.g., because you're doing financial work and this affects the direction that something rounds later on, use the decimal module.

Final note: In Python 3.x and Python 2.7, the repr of a float has changed so that you will actually get 4.123 as you expect here.


If you want to have an exact representation of your floating point number, you have to use decimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消