[Tutor] Floating point number problem...............
Magnus Lyckå
magnus at thinkware.se
Fri May 23 08:49:27 EDT 2003
At 05:07 2003-05-23 -0700, Python-lover wrote:
> I have a problem in floating point number.
It's not you. :) It's the way they are represented in
computers in general. Note for instance that:
>>> if 0.2 + 0.4 == 0.6:
... print "same"
... else:
... print "not same"
...
not same
The only way to avoid this would be to use a completely different
way of storing fractions in computers, but every way we might use
will have disadvantages. There are discussions in the Python
community do create a standard fixed point type, but it's not
here yet. There is some standardization work in progress that we
are waiting for...
>I assgined a value, say 1.23456, to a variable. When i printed the
>variable i got 1.234560000000001 instead of 1.23456. How can i get the
>original value?
Just as 1/3 can't be stored exactly as a decimal number, 123456/100000 can't
be stored exactly as a binary number. It will be stored as the closest
binary approximations.
See Appendix B in the Python Tutorial:
http://www.python.org/doc/current/tut/node14.html
Use "print" to display fewer decimals. See also my recent mail
with subject "Re: [Tutor] Handling international characters"
for more about the difference between repr and string.
The print statement uses str() while just typing a varable name
followed by enter uses repr()
>>> f = 0.1
>>> f
0.10000000000000001
>>> print f
0.1
>>> str(f)
'0.1'
>>> repr(f)
'0.10000000000000001'
>Moreover how to have a floating point number that has only 3 numbers
>after decimal point even the number has got more digits after the decimal
>point? I tried with "round" function but it is rounding the 3rd
>digit instead of keeping it as it is.
You can use format strings.
>>> f = 1./3
>>> f
0.33333333333333331
>>> print f
0.333333333333
>>> print round(f, 3)
0.333
>>> round(f, 3)
0.33300000000000002
>>> print "%.3f" % f
0.333
>>> "%.3f" % f
'0.333'
>>>
--
Magnus Lycka (It's really Lyckå), magnus at thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program
More information about the Python-list
mailing list