mardi 29 décembre 2015

Python randint returns slightly off versions of numbers? [duplicate]

This question already has an answer here:

I'm trying to write a program to generate all the possible configurations of European money to make 2 Euros, but when I try to use randint to choose a random number from my list, it returns the numbers with a few extra numbers at the end.

pence = [.01, .02, .05, .1, .2, 1, 2]
from random import randint
for i in range(200):
    add = [0]
    while sum(add) < 2:
        add.append(pence[randint(0, 6)])
    print (add)
    print (sum(add))
    print ("")

It returns this:

[0, 0.050000000000000003, 2]
2.0499999999999998

I'm not sure how to round this number. How do I get it to stop giving me strange numbers?




Aucun commentaire:

Enregistrer un commentaire