This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Integer conversion failure
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: eryksun, nvutri, serhiy.storchaka
Priority: normal Keywords:

Created on 2017-04-07 04:02 by nvutri, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
int_bug.py nvutri, 2017-04-07 04:02 Code to reproduce error for int
Messages (3)
msg291249 - (view) Author: Tri Nguyen (nvutri) Date: 2017-04-07 04:02
This code below shows a situation when Python int() library would return a value of int(1.0) -> 0.0

---------------CODE----------------------------
CHANGES = [1.00, 0.50, 0.25, 0.10, 0.05, 0.01]

# This code was originally to solve the least number of changes needed.
# However, in an attempt to solve this. A bug is found.

def get_change(R):
    for change in CHANGES:
        # This division and int() is where failure is happening
        num = int(R / change)
        # This printing line shows the failure.
        print 'int(%s)\t = %s' % (R / change, num)
        R = R - num * change
    print 'R = %s' % R

get_change(4.01)

-------------OUTPUT----------------------

int(4.01)	 = 4
int(0.02)	 = 0
int(0.04)	 = 0
int(0.1)	 = 0
int(0.2)	 = 0
int(1.0)	 = 0    # This should be 1, right?
R = 0.01
msg291250 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2017-04-07 04:19
Use %r instead of %s to show the repr. Hopefully that should clear things up for you. int() truncates toward 0. The float in this case is slightly less than 1.
msg291251 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2017-04-07 04:20
"%s" rounds float representation to 12 digits in Python 2.7. Replace "%s" with "%r" and you will get precise representation of floats.

int(4.01)        = 4
int(0.019999999999999574)        = 0
int(0.03999999999999915)         = 0
int(0.09999999999999787)         = 0
int(0.19999999999999574)         = 0
int(0.9999999999999787)  = 0
R = 0.009999999999999787

See also https://docs.python.org/2/tutorial/floatingpoint.html .
History
Date User Action Args
2022-04-11 14:58:45adminsetgithub: 74195
2017-04-07 04:20:16serhiy.storchakasetnosy: + serhiy.storchaka
messages: + msg291251
2017-04-07 04:19:16eryksunsetstatus: open -> closed

nosy: + eryksun
messages: + msg291250

resolution: not a bug
stage: resolved
2017-04-07 04:02:05nvutricreate