rofls
rofls

Reputation: 5115

Why are these results so different when using Python's "float" function?

My Python code was doing something strange to me (or my numbers, rather):

a)

float(poverb.tangibles[1])*1000
1038277000.0

b)

float(poverb.tangibles[1]*1000)
inf

Which led to discovering that:

long(poverb.tangibles[1]*1000)

produces the largest number I've ever seen.

Uhhh, I didn't read the whole Python tutorial or it's doc. Did I miss something critical about how float works?

EDIT:

>>> poverb.tangibles[1]
u'1038277'

Upvotes: 3

Views: 130

Answers (1)

BrenBarn
BrenBarn

Reputation: 251345

What you probably missed is docs on how multiplication works on strings. Your tangibles list contains strings. tangibles[1] is a string. tangibles[1]*1000 is that string repeated 1000 times. Calling float or long on that string interprets it as a number, creating a huge number. If you instead do float(tangibles[1]), you only get the actual number, not the number repeated 1000 times.

What you are seeing is just the same as what goes on in this example:

>>> x = '1'
>>> x
'1'
>>> x*10
'1111111111'
>>> float(x)
1.0
>>> float(x*10)
1111111111.0

Upvotes: 17

Related Questions