1

I'm trying to plot the results of a simple ODE, but the graph line isn't showing in the plot window. See the code below:

import numpy as np
import matplotlib.pyplot as plt


class ForwardEuler_v1(object):
    def __init__(self, f, U0, T, n):
        self.f, self.U0, self.T, self.n = f, U0, T, n
        self.dt = T / float(n)
        self.u = np.zeros(n + 1)
        self.t = np.zeros(n + 1)

    def solve(self):
        """Compute solution for 0 <= t <= T."""
        self.u[0] = float(self.U0)
        self.t[0] = float(0)

        for k in range(self.n):
            self.k = k
            self.t[k + 1] = self.t[k] + self.dt
            self.u[k + 1] = self.advance()
        return self.u, self.t

    def advance(self):
        """Advance the solution one time step."""
        u, dt, f, k, t = self.u, self.dt, self.f, self.k, self.t

        u_new = u[k] + dt * f(u[k], t[k])
        return u_new


def f(u, t):
    return u


solver = ForwardEuler_v1(f, U0=1, T=3, n=15)
u, t = solver.solve()

fig, ax = plt.subplots(1, 1)
ax.plot = (t[0:], u[0:])

plt.show()

The returns from solver.solve() give t with a shape of (16,) and u with a shape of (16,).

Can anyone let me know if this works for them or if I'm plotting this wrong?

1 Answer 1

1

The problem is that you are not passing the t and u arguments to the plot command. Currently, you are assigning a (t, u) tuple to the plot function and therefore you see an empty graph.

You need to replace the line

ax.plot = (t[0:], u[0:])

by

ax.plot(t[0:], u[0:])
Sign up to request clarification or add additional context in comments.

1 Comment

It sure did and I will. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.