La clase...
class ForwardEuler: def __init__(self, f, dt): self.f, self.dt = f, dt def set_initial_condition(self, u0, t0=0): self.u = [] self.t = [] self.u.append(float(u0)) self.t.append(float(t0)) self.k = 0 def solve(self, T): tnew = 0 while tnew <= T: unew = self.advance() self.u.append(unew) tnew = self.t[-1] + self.dt self.t.append(tnew) self.k += 1 return numpy.array(self.u), numpy.array(self.t) def advance(self): u, dt, f, k, t = \ self.u, self.dt, self.f, self.k, self.t[-1] unew = u[k] + dt*f(u[k], t) return unew
Utilizando la clase:
def _f1(u, t): return 0.2*u*(1-u) u0 = 0.1 dt = 0.1 T = 40 method = ForwardEuler(_f1, dt) method.set_initial_condition(u0, 0) u, t = method.solve(T) g1=line([[t[i],u[i]] for i in range(len(u))],rgbcolor=(1/4,1/8,3/4)) g2 = text("Ec. Log.", (20, 1)) g = g1+g2 show(g, xmin=0, xmax=41, ymin=0, ymax=1)
No hay comentarios:
Publicar un comentario