![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Professional Programmer
Join Date: Feb 2005
Posts: 434
Rep Power: 4
![]() |
I worked on a tutorial about list comprehension and this happened (Python v2.3) ...
# a list of approximated pi values rounded off using list comprehension # is supposed to give: # ['3.1', '3.14', '3.142', '3.1416', '3.14159'] # but gives: # ['3.1000000000000001', '3.1400000000000001', '3.1419999999999999', # '3.1415999999999999', '3.1415899999999999'] piList = [repr(round(355/113.0, k)) for k in range(1,6)] print piList # this however gives the right result = 3.14159 print round(355/113.0, 5)
__________________
I looked it up on the Intergnats! |
|
|
|
|
|
#2 |
|
Programmer
Join Date: Feb 2005
Posts: 67
Rep Power: 4
![]() |
My first guess would be, that it has got something to do with the type of numbers you use. You could try it with long numbers...
I don't have a version of python available right now, So I can only guess Would you mind explaining list comprehensions to me for starters??? |
|
|
|
|
|
#3 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
Python likes its rounding errors - no idea why.
|
|
|
|
|
|
#4 | |
|
Professional Programmer
Join Date: Feb 2005
Posts: 434
Rep Power: 4
![]() |
Quote:
list comprehension:
result = [expression for item1 in sequence1 [if condition1]
[for item2 in sequence2 ... for itemN in sequenceN]
]
is equivalent to:
result = []
for item1 in sequence1:
for item2 in sequence2:
...
for itemN in sequenceN:
if (condition1) and further conditions:
result.append(expression)
__________________
I looked it up on the Intergnats! |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|