Python Forum

Full Version: New guy looking at lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello folks :

Version/system stats:

Quote:@localhost ~]$ python -V
Python 2.6.6
@localhost ~]$ cat /etc/*release | tail -1
CentOS release 6.10 (Final)

My cheap g code ...

#!/usr/bin/python
list = ['abcd', 786, 2.23, 'john', 70.2]
print(list)
print list
list.append(7)
print(list)
The output :

Quote:@localhost ~]$ ./pyte
['abcd', 786, 2.23, 'john', 70.200000000000003]
['abcd', 786, 2.23, 'john', 70.200000000000003]
['abcd', 786, 2.23, 'john', 70.200000000000003, 7]

The ask:
Why do I see "70.200000000000003" ??

Thanks in adv folks.
Floating point arithmetic. Decimals are stored as a fraction that approximates the correct value. It is sometimes off by a teeny little bit, as you see in your example.
Ummm .. so how do I work around this in actual execution.
This is just something I found in a tutor.

But if it were real world .. how would I realize that what, lets say, I'm using for a conditional branch isn't quite what I think it is ... Know ?

70.2 isnt the same as 70.20000003. I guess printing out every single list that may contain this issue then script around it. Yeah ?
You could use round() or import the decimal module to remove the extra digits.
It's the way floating point arithmetic work,Basic Answers | Python doc.
Quote:But if it were real world .. how would I realize that what, lets say, I'm using for a conditional branch isn't quite what I think it is ... Know ?
For finical calculation or for it to work as you learn at school,use Decimal module.
>>> 0.4 - 0.1
0.30000000000000004

>>> from decimal import Decimal
>>> Decimal('0.4') - Decimal('0.1')
Decimal('0.3')
Other possible techniques include testing the difference against a really small value or using integers (as in, calculate in pennies instead of fractions of a dollar).

epsilon = 1 / 10 ** 15
...
if abs(x - y) < epsilon:
    # basically equal