Python Forum

Full Version: Simple Code - Strange Results?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here's a simple code I ran for practice as part of my class. Below are the results. Can anyone tell me why the increment when to the ?trillionth+? decimal place and not the thousandth that I specified?

import os
import sys
import re

votes=3
while True:
    votes=votes + .001
    print(votes)
    if votes>=5:
        break
Result(portion of...)
4.9870000000002195
4.98800000000022
4.98900000000022
4.9900000000002205
4.991000000000221
4.992000000000221
4.9930000000002215
4.994000000000222
4.995000000000222
4.9960000000002225
4.997000000000223
4.998000000000223
4.9990000000002235
5.000000000000224
As soon as you add a float to an int, the int becomes a float.
Floats are made up of two values, the exponent and mantissa, so you can not expect that
floating point will be exact, but very close.
Understood. Thank you very much
Floating point arithmetic is notoriously imprecise because of how computer hardware handles floating point numbers. The trillionths arise from that imprecision.
Some point on round() and force decimal places {:.2f} --> 2 decimal places.
votes = 3
while True:
    votes = votes + .001
    print(round(votes, 3))
    #print('{:.2f}'.format(votes))
    if votes >= 5:
        break
To overcome it decimal,can be important in eg finance calculation.
from decimal import Decimal

votes = Decimal('3')
while True:
    votes = votes + Decimal('.001')
    print(votes)
    if votes >= 5:
        break
Output:
.... 4.990 4.991 4.992 4.993 4.994 4.995 4.996 4.997 4.998 4.999 5.000
i ran your code in python 2.7 it looped all the way to 5.0, each result either less or equal to number of decimal spaces you specified