Justin Haddock
Justin Haddock

Reputation: 3

Weird output of python division

I have this function

def getXVals(maxVal = 100):
    listt = []
    i = 1
    while i != 11:
        listt.append(float(maxVal/i))
        i += 1

which is returning

[100.0, 50.0, 33.333333333333336, 25.0, 20.0, 16.666666666666668, 14.285714285714286, 12.5, 11.11111111111111, 10.0]

and I want it to return even intervals. What am I doing wrong?

Upvotes: 0

Views: 94

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799230

Approximately everything. If you want a linear interpolation from 0 to x with n steps then you need to multiply x by k/n where k goes from 0 to n. You... don't do this.

[maxVal * k / 10 for k in range(0, 11)]

Upvotes: 3

Related Questions