Python Forum
New guy looking at lists - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: New guy looking at lists (/thread-15621.html)



New guy looking at lists - sumncguy - Jan-24-2019

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.


RE: New guy looking at lists - ichabod801 - Jan-24-2019

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.


RE: New guy looking at lists - sumncguy - Jan-24-2019

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 ?


RE: New guy looking at lists - stullis - Jan-24-2019

You could use round() or import the decimal module to remove the extra digits.


RE: New guy looking at lists - snippsat - Jan-24-2019

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')



RE: New guy looking at lists - ichabod801 - Jan-24-2019

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