Float + min/max?
Gary Herron
gherron at islandtraining.com
Wed Aug 20 02:09:15 EDT 2003
On Tuesday 19 August 2003 06:55 pm, Shu-Hsien Sheu wrote:
> Hi,
>
> I am new to Python, and just wrote a small program to generate the maximum
> number of the cartisian coordinates among all atoms in a given molecule.
> However, I found the float function, if combined with max function, to be
> kind of confusing. It would give a number with uneccessary decimals from
> nowhere.
>
> Not converting to float:
>
> x = []
> for i in (0, length-2):
> slines[i] = lines[i].split()
> if slines[i][0] == "ATOM":
> x.append(slines[i][6])
>
> print "xmax = " + max(x) + " " + "xmin = " + min(x)
>
> Output:
> xmax = 90.179 xmin = 64.112
>
>
> Converting to float numbers:
>
> x = []
> for i in (0, length-2):
> slines[i] = lines[i].split()
> if slines[i][0] == "ATOM":
> x.append( float(slines[i][6]) )
>
> print "xmax = " + max(x) + " " + "xmin = " + min(x)
>
> Output:
> xmax = 90.179000000000002 xmin = 64.111999999999995
>
>
> The original data file apparantly does not have those decimals. May I ask
> how does it happend? Thank!
>
> -shuhsien
This is a *feature* of all floating point numbers in any language on
any computer. See the following URL's for more information.
>From the FAQ:
http://www.python.org/cgi-bin/faqw.py?req=all#4.98
and a manual page:
http://www.python.org/doc/current/tut/node14.html
The solutions: Learn to life with floating point numbers and their
approximate representation on any computer, or explicitly control the
output format like this:
>>> t = 1.0/3.0
>>> print t
0.333333333333
>>> print '%6.2f' % t
0.33
>>>
Gary Herron
More information about the Python-list
mailing list