Nick Charlton Nick Charlton - 2 days ago 5
Python Question

Strange values whilst using list comprehension

I am trying to make a function create_plot_data(xmin, xmax, n) that produces a list (xs) of values based on the equation:
equation

This is the code I came up with:

def create_plot_data(xmin, xmax, n):
xs = [xmin + i * ((xmax - xmin) / n - 1) for i in range(n)]
return xs


but when I test it with:

create_plot_data(0, 2, 5)


I get:

[0.0, -0.6, -1.2, -1.7999999999999998, -2.4]


Whereas, I know I should be getting (calculated manually):

[0.0, 0.5, 1.0, 1.5, 2.0]


Does anyone know what is going wrong?!

Answer

You missed some parens: ... + i * ((xmax - xmin) / ( n - 1 ) ).

Comments