Issue 3024: Integer conversion inconsistent (original) (raw)

Created on 2008-06-01 22:31 by helminthe, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (6)
msg67609 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:31
This issue is probably older than I am, and was amazed to discover it in python: Python 2.5.2 (r252:60911, May 7 2008, 15:19:09) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 >>> int(float("-23.15")) -23 >>> int(float("-23.65")) -23 >>> int(float("24.9")) 24 >>> int(float("24.4")) 24 Is this by design? What is the python way of obtaining a correct result?
msg67612 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2008-06-01 22:41
I don't see any problem with that result? Why do you consider the result incorrect, and what "correct" result would you have inspected instead? Notice that int conversion of floats truncates them, by definition.
msg67613 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:44
Hello, As far as I know, the correct conversion is to either round to the nearest, or to the smaller integer, but not both.
msg67614 - (view) Author: Razvan Cosma (helminthe) Date: 2008-06-01 22:45
Sorry for not writing completely above - python does neither, it rounds to the integer closest to zero
msg67615 - (view) Author: Martin v. Löwis (loewis) * (Python committer) Date: 2008-06-01 22:49
I see. There is no such thing as a "correct" conversion from real numbers to integer numbers. Instead, there are various approaches, called "truncating", "rounding", "flooring", and "ceiling". Python's default conversion is truncation, and it is consistent in doing so: int(x) will return the nearest integer between 0 and x. If you want rounding, use the round builtin.
msg67616 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2008-06-01 22:51
This is exactly what int() is supposed to do. For other kinds of rounding, look at round(), math.floor(), math.ceil(), and many rounding options in the decimal module: from decimal import Decimal >>> Decimal('-23.15').to_integral(ROUND_FLOOR) Decimal("-24") >>> Decimal('-23.15').to_integral(ROUND_CEILING) Decimal("-23") >>> Decimal('-23.15').to_integral(ROUND_DOWN) Decimal("-23") >>> Decimal('-23.15').to_integral(ROUND_HALF_EVEN) Decimal("-23")
History
Date User Action Args
2022-04-11 14:56:35 admin set github: 47274
2008-06-01 22:51:35 rhettinger set nosy: + rhettingermessages: +
2008-06-01 22:49:54 loewis set status: open -> closedresolution: not a bugmessages: +
2008-06-01 22:45:56 helminthe set messages: +
2008-06-01 22:44:12 helminthe set messages: +
2008-06-01 22:41:08 loewis set nosy: + loewismessages: +
2008-06-01 22:31:17 helminthe create