3

I am new to python, so I expect that I am missing some basic knowledge of types here. I am trying to create a string where I take a floating point number and replace decimal point with a string. In doing so I tried calling a line of code that is equivalent to:

int(pow(10, 1)*(5.1%1)))

But if you run this code:

x = pow(10, 1)*(5.1%1)
print(x)
print(type(x))
print(int(x))
print(int(1.0))
print(type(1.0))

It returns:

1.0
<type 'float'>
0
1
<type 'float'>

I assumed there is a type problem here but they are both type float. So why does int(x) return zero but not int(1.0)?

ldoiron17
  • 33
  • 3

1 Answers1

2

Due to rounding error, you didn't get exactly 1, but a bit less

>>> x = pow(10, 1)*(5.1%1)
>>> print '{:.20f}'.format(x)
0.99999999999999644729

You are just getting a bunch of other things rounding up for you when you display it

>>> x = pow(10, 1)*(5.1%1)
>>> print x
1.0
>>> print '{:.10f}'.format(x)
1.0000000000

To get something displayed that will definitely give the same number (slightly better for debugging), use repr out of habit

>>> x = pow(10, 1)*(5.1%1)
>>> print repr(x)
0.9999999999999964
>>> print 'hello {!r} world'.format(x)
hello 0.9999999999999964 world
Mike Graham
  • 73,987
  • 14
  • 101
  • 130