Float + min/max?
Mel Wilson
mwilson at the-wire.com
Wed Aug 20 10:05:42 EDT 2003
In article <mailman.1061352037.8475.python-list at python.org>,
"Shu-Hsien Sheu" <sheu at bu.edu> 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
I think you misunderstand what's going on here. At this
point x contains strings. If you coded
print max(x) + min(x)
you would see
90.17964.112
and if you then coded
x.append ('123.3')
print "xmax = " + max(x) + " " + "xmin = " + min(x)
you'd get
xmax = 90.179 xmin = 123.3
so conversion to float is not something you can skip.
>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!
Short answer, you want to format your float results (not
just these, any float results) when you print them:
print "xmax = %6g xmin = %6g" % (max(x), min(x))
or
print "xmax = %6.3f xmin = %6.3f" % (max(x), min(x))
or for the die-hard scientific
print "xmax = %6e xmin = %6e" % (max(x), min(x))
Regards. Mel.
I was going to bitch about %6f printing 6 places of
decimals instead of a total field width of 6, but I see C
does this too. Python-specific '%6g' prints a 6-character
field. Very nice.
MPW
More information about the Python-list
mailing list