Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
New guy looking at lists
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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 ?
Reply
#4
You could use round() or import the decimal module to remove the extra digits.
Reply
#5
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')
Reply
#6
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
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,190 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020