Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
graphing euler method
#1
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()
Reply
#2
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( )   
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Forcing matplotlib to NOT use scientific notation when graphing sawtooth500 4 222 Mar-25-2024, 03:00 AM
Last Post: sawtooth500
  Calculate the Euler Number with more decimal places Pedroski55 10 4,392 Oct-31-2021, 04:45 AM
Last Post: Pedroski55
  graphing inequalities Dasiey12 0 3,422 Mar-30-2021, 01:47 AM
Last Post: Dasiey12
  IndexError in Project Euler attempt CRISPRmetoopls 3 2,268 Aug-10-2020, 10:00 AM
Last Post: perfringo
  Help Graphing Arduino Data Real Time in Python nschulz 0 2,496 Mar-12-2020, 06:15 PM
Last Post: nschulz
  Matplotlib graphing help (dual y axis, groupby, filter) keml 0 2,165 Feb-07-2020, 02:35 AM
Last Post: keml
  Graphing from a while loop McDweevo 1 2,837 Nov-13-2019, 08:02 PM
Last Post: micseydel
  Graphing three database in one graph Python r_e 1 2,338 Jun-20-2019, 05:10 PM
Last Post: r_e
  3rd problem from project Euler Richard_SS 6 3,116 Jun-05-2019, 02:06 PM
Last Post: DeaD_EyE
  Graphing process execution time Temennigru 4 4,714 Nov-15-2017, 11:54 PM
Last Post: Temennigru

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020