Python Forum

Full Version: graphing euler method
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My program should Sketch the graph of ?(?) and the approximations ?ℎ(??) with ℎ=1,0.5,0.1 where p(t) is the approximation using Euler's method. I'm new to python and for some reason, I'm not getting three graphs for the three different h values, how can I fix this?

import numpy as np
import matplotlib.pylab as plt
def Euler():
    K = 12; r = 0.43; Po = 1; N=30;
    h=[.1,.5,1]
    #defining dP/dt as a function f(P)
    f = lambda P: r*P*(1-P/K)
  
    P = np.array([])
    P = np.append(P,Po) #initializing P with Po
    
    for i in range (len(h)):
        for n in range(N+1):#n=0 as index for P[0], then 1<=n<=N
            Pn = P[n] + h[i]*f(P[n]) #euler
            P = np.append(P,Pn) 
    plt. plot ( n, P[n] , 'ro' )
    plt. xlabel (' Value of n ”' )
    plt. ylabel (" Value of p[n] ”")
    plt. title (" Approximate Solution with Euler’s Method " )
    plt. show ( )   
Euler()
I slightly rewrote your code, you can adapt it for your needs.

import numpy as np
import matplotlib.pylab as plt

def volterra(P, K=1, r=1):
    return r * P * (1 - P / K)

def euler(fun, Po, h, N, **kwargs):
    acc = [Po]
    times = np.cumsum(np.r_[0, np.ones(N) * h])
    for _ in range(N):
        acc.append(acc[-1] + h * fun(acc[-1], K=K, r=r))  # for autonomous system's only
    return np.array(acc), times

K = 12
r = 0.43
Po = 1
N = 30;
step_values = [1, 0.5, 0.1]
fig = plt.figure()
ax = fig.add_subplot(111)
for h, c in zip(step_values, 'rgb'):
    Ps, Ts = euler(volterra, Po, h, N, K=K, r=r)
    ax.plot(Ts, Ps, c)

plt.show( )