list - multidimensional Euler's method python -
so have coded function euler's method. however, want able use initial conditions arbitrary dimensions. example, functions works using this:
>>>euler(f, x0, t0, h, n) where x0 float. want able use this:
>>>euler(f, [x0], t0, h, n) where x0 list of floats. (making multidimensional)
f = function, x0 = initial conditions @ time t0,
t0 = initial time, h = step size, n = number of steps.
i have tried using loop:
def euler(f,x0,t0,h,n): t = t0 y = x0 z = [] v = [] in y: while t <= n: xval = t yval = [y] t += h y += h * f(t,y[i]) #i have tried y+= h*f(t, i) z.append(xval) v.append(yval) return z, v the error typeerror: list indices must integers or slices, not float. understand, meaning have index y, using y[0], y[1], etc...but when do
y+= h* f(t, y[:])
it gives me error regarding other function in file : f = >
typeerror: float required line 22, in <module> vv = -x**3 - x + sin(t) when try
y += h * f(t, y[0]) and enter
>>>euler(f, [0., 1.], 0., 1, 10) line 15, in <module> y += h * f(t,y[0]) builtins.typeerror: 'float' object not iterable i want return 2 lists, first list z, returns list of time values, , second list v, returns list of list of each of results during each step. far has worked used float not list. code missing?
try this:
def euler(f,x0,t0,h,n): t = t0 z = [] v = [] y in x0: while t <= n: xval = t yval = [y] t += h y += h * f(t,y) #i have tried y+= h*f(t, i) z.append(xval) v.append(yval) return z, v i don't know if intended method seeing y += h * f(t,y) dead code , not used anywhere else
i believe error due not paying attention types of variables. y list when did y = x0.
fast-forward line y += h * f(t,y[i]). in here try use += operator on y , append contents of iterable y.
in same statement, try index y using i. index list, need use integer, since i element of y (which array of floats), i cannot used index list, , why can error:
typeerror: list indices must integers or slices, not float.
also when y+= h* f(t, y[:]), error:
typeerror: float required
because y[:] creates new list elements of y, still passing list function.
finally when y += h * f(t, y[0]), error:
builtins.typeerror: 'float' object not iterable
because mentioned before, y list , += on list appends contents of iterable current list. way "iterate" on second list , append items in second list first. since value h * f(t, y[0]) not list, , not iterable either, error
Comments
Post a Comment