Python doesn't know how to do math?

David Bolen db3l at fitlinxx.com
Thu Apr 25 20:21:20 EDT 2002


Chris Spencer <clspence at one.net> writes:

> 	I want to thank everyone who responded to this.  I read the
> floating point tutorial and now understand the issues.  I wasn't
> really looking for that much precision anyways (2 decimal places was
> all I really need).  So now that I know, I shant ask again.

Note that using str() (itself, or via print, or the '%s' formatting
operator) will give you a reasonable presentation, but the amount of
precision may vary and not under your control.

One way to ask for specific precision is by using the '%f' formatting
operator, e.g.:

    >>> value = 5.0/100.0
    >>> repr(value)
    '0.050000000000000003'
    >>> str(value)
    '0.05'
    >>> '%f' % value
    '0.050000'
    >>> '%6.2f' % value
    '  0.05'
    >>> '%.2f' % value
    '0.05'
    >>> '%.4f' % value
    '0.0500'

> BTW, this is one thing I love about the Python community.  Ask a
> stupid question and you get good and helpful answers.

While declaring Python unable to do math as in your subject line may
have been a bit presumptuous, I don't think the question itself is
stupid (common maybe, thus the FAQ and documentation, but not stupid).
It can be very easy to overlook the binary nature of most floating
point systems nowadays until you get burned the first time.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list