0
def fc_range(start, end, step=1.0):
    while start < end:
        yield start
        start +=step
for x in fc_range(0, 1, 0.05):
    print x # look the ans
print list(fc_range(0, 1, 0.05)) # compare the ans now

and when I test this:

>>> 0.1 + 0.05
0.15000000000000002

it seems like to be clear, but why when I use print the answer is not 0.15000000000000002 ?

FaiChou
  • 767
  • 7
  • 16
  • What do you mean by "when I use print the answer is not 0.15000000000000002"? It is here. – wRAR Apr 29 '16 at 13:24

2 Answers2

2

To start with, floating point maths are not exact because most floating point numbers can NOT be represented exactly with float.

As a result, the value of 0.1 + 0.15 are not exactly 0.25, but some number very close to it.


The reason that print gives you a seemingly exact result is because, it uses str to get the result, which is the user-friendly string representation.

>>> str(0.1 + 0.05)
'0.15'

The Python interpreter, on the other hand, uses repr, which gives you the as-code string representation:

>>> repr(0.1 + 0.05)
'0.15000000000000002'
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

That's because print calls float's __str__ method under the hood and for some reason __str__ on floats does rounding.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • You wouldn't really want `__str__` *not* to round, would you? Without any rounding, `1/100.0` would print as `0.01000000000000000020816681711721685132943093776702880859375`, for example. – Mark Dickinson Apr 30 '16 at 19:32
  • @MarkDickinson And what is wrong with that? You prefer lie over truth? Implicit rounding is at least confusing. Not to mention that Python is not following its own zen: "explicit is better then implicit". – freakish May 01 '16 at 13:10
  • What's wrong with it is that it produces an insane number of digits for small or large floats. For example, the true value stored for `1e-300` gives a string of length 756 if written exactly (750 digits, an exponent and a decimal point). So yes, in the spirit of the Zen: "Practicality beats Purity", and it's impractical to show all 750 digits. – Mark Dickinson May 01 '16 at 13:16