Numbers in python

Fredrik Lundh fredrik at pythonware.com
Fri Mar 10 10:01:44 EST 2006


brainy_muppet at hotmail.com wrote:

> Basically, I have a code with is almost finished but I've having
> difficultly with the last stage of the process. I have a program that
> gets assigns different words with a different value via looking them up
> in a dictionary:
>
> eg if THE is in the writing, it assigns 0.965
>
> and once the whole passage is read it returns all the numbers in the
> format as follows:
>
> ['0.965', '1.000', '0.291', '1.000', '0.503']
>
> However, I can't seem to get the program to treat the numbers as
> numbers. If I put them in the dictionary as 'THE' = int(0.965) the
> program returns 1.0 and if I put 'THE' = float(0.965) it returns
> 0.96555555549 or something similar. Neither of these are right!

int(0.965) is 0 and int("0.965") is an error, so I'm not sure what you
did to get 1.0.

but 0.965 and 0.96499999999999997 is indeed the same thing, when
stored as binary floating point numbers:

    >>> 0.965
    0.96499999999999997
    >>> 0.965 == 0.96499999999999997
    True

for an explanation, see this page:

    http://docs.python.org/tut/node16.html

in your case, explicitly formatting the numbers on the way might be good
enough, e.g.

    print "%.3f" % value

for details, see:

    http://docs.python.org/lib/typesseq-strings

if you really need support for decimal floating point arithmetics, see:

    http://docs.python.org/lib/module-decimal.html

</F> 






More information about the Python-list mailing list