Reputation: 844
D1_inv
Out[23]: [0.024799999999999999, 0.029600000000000001, 0.035799999999999998]
I'm trying to round these figures upto 4 decimal places. I've used this:
for i in D1_inv:
round(i,4)
But the output remains the same as above. Can somebody help me here?
Upvotes: 1
Views: 10753
Reputation: 438
D1_inv = [0.024799999999999999, 0.029600000000000001, 0.035799999999999998]
for i in D1_inv:
print round(float(i), 4)
Output:
0.0248
0.0296
0.0358
Upvotes: 3
Reputation: 14399
What you're seeing is floating-point errors. Often it's not mathematically possible to represent a base 10 decimal in base 2 (i.e. as a float
) exactly, so your computer gets as close as it can. But if your output style is set to show many decimal places, these "errors" will show up.
round
doesn't help because its output is still a float
. You can't really fix this in any simple way, as it is an artefact of binary math. Some options are:
frac
.format
(but this makes them strings)Upvotes: 3
Reputation: 57033
Your problem is a perfect case for list comprehension:
D1_inv = [round(i,4) for i in D1_inv]
print(D1_inv)
#[0.0248, 0.0296, 0.0358]
Upvotes: 3
Reputation: 800
You are not saving the result.
for i, x in enumerate(D1_inv):
D1_inv[i] = round(x, 4)
Upvotes: 0