Python float representation error?

M

mailpitches

try running this in python:

print [39.95]

the output i get is:
[39.950000000000003]

what's up with that?
 
J

James Stroud

try running this in python:

print [39.95]

the output i get is:
[39.950000000000003]

what's up with that?

This comes from the imprecision in representing base-10 fractions as
binary. Try "print [str(39.95)]".

If you want to print a list, maybe:

print map(str, alist)

James

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 
D

Dennis Lee Bieber

try running this in python:

print [39.95]

the output i get is:
[39.950000000000003]

what's up with that?

Nothing's up...

Standard computer science -- floating point numbers are not exact.

You shoved the number into a list (the []), and since lists don't
have a "clean" printable form, you get the repr() format for the list
and its contents.

Python normally cleans up the "noise" in floating point numbers when
printed directly. repr(), however, shows the number to the best of the
internal storage format.
alst = [anum]
print alst, str(alst), repr(alst) [39.950000000000003] [39.950000000000003] [39.950000000000003]

for an in alst:
.... print an, str(an), repr(an)
....
39.95 39.95 39.950000000000003.... def __str__(self):
.... return "I'm a C"
.... def __repr__(self):
.... return "I think I'm a C at %s" % id(self)
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,134
Latest member
JavierIlif

Latest Threads

Top