1

Basically I thought I created a loop to just increase .1 every iteration. What I have got is these numbers below like 0.30000000000000004,0.7999999999999999, 3.0000000000000013. Here is my code and the results. Why is it not .1, .2. .3, etc. and/or why is it 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, etc. Basically why are their unexpected, for me, decimals.

>>> tph_bin = []
>>> bin_num = 0
>>> while bin_num <= 3.5:
    tph_bin.append(bin_num)
    bin_num = bin_num + .1


>>> tph_bin
[0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999, 0.9999999999999999, 1.0999999999999999, 1.2, 1.3, 1.4000000000000001, 1.5000000000000002, 1.6000000000000003, 1.7000000000000004, 1.8000000000000005, 1.9000000000000006, 2.0000000000000004, 2.1000000000000005, 2.2000000000000006, 2.3000000000000007, 2.400000000000001, 2.500000000000001, 2.600000000000001, 2.700000000000001, 2.800000000000001, 2.9000000000000012, 3.0000000000000013, 3.1000000000000014, 3.2000000000000015, 3.3000000000000016, 3.4000000000000017]

Bonus Question: Is there a better way to create a list of numbers increasing by .1?

Don Quixote
  • 145
  • 1
  • 8

3 Answers3

2

This is a floating point precision limitation. Please refer to:

https://docs.python.org/2/tutorial/floatingpoint.html

0.1 is actually stored as the binary fraction:

0.00011001100110011001100110011001100110011001100110011010

As you can see, that can lead to binary rounding errors as numbers are added.

Try using Decimal as an alternative if all you care is 1 decimal place precision:

from decimal import *
value = Decimal("0.1")+Decimal("0.1")+Decimal("0.1")
print value
# 0.3
if Decimal('0.3') == value
  print 'This works!'
PressingOnAlways
  • 11,948
  • 6
  • 32
  • 59
-1

Answer to Bonus Question: Is there a better way to create a list of numbers increasing by .1?

with numpy

numpy.arange(0,3.5,0.1)
karakfa
  • 66,216
  • 7
  • 41
  • 56
-1

Its basically the disadvantages of using float numbers. The number 0.2 plus 0.1 just got overflowed and the result wont fit inside a memory block reserved to float types so it cuts of the part overflowed and rounds it around that value. If you want to work with numbers that way, you should operate with integers and then divide the result by 10 or just round up the values, but never try to compare floats by value because the outcome could be surprising.

Tacsiazuma
  • 746
  • 5
  • 11
  • Thanks. I would have never thought of that. I changed by code to the below and it worked! I really appreciate it. for num in range(35): bin_num = (num / 10) tph_bin.append(bin_num) num =+ 1. I can't get the formatting to work but you're a smart guy. Appreciate it. – Don Quixote Jul 14 '16 at 21:23