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) *  |
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) *  |
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) *  |
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") |
|
|