Bottom Page

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()
Quote
#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( )   
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  What is the use of call method and when to use it? everyday1 1 58 Jul-14-2019, 01:02 PM
Last Post: ichabod801
  Method not defined diskt 1 113 Jul-03-2019, 12:55 PM
Last Post: noisefloor
  Graphing three database in one graph Python r_e 1 152 Jun-20-2019, 05:10 PM
Last Post: r_e
  Method not regocnized Lass86 3 182 Jun-19-2019, 09:03 AM
Last Post: Lass86
  3rd problem from project Euler Richard_SS 6 272 Jun-05-2019, 02:06 PM
Last Post: DeaD_EyE
  web3 method rembrandt 3 150 Jun-04-2019, 05:43 PM
Last Post: buran
  [split] help with While method peterd1965 3 604 Jun-20-2018, 05:45 PM
Last Post: volcano63
  help with While method brawdhampshire 5 1,145 Jun-20-2018, 05:38 PM
Last Post: micseydel
  need method to look up dictionary key by value league55 3 568 Jan-17-2018, 10:58 PM
Last Post: metulburr
  Best Method for simple GUI? PythonAndArduino 4 1,056 Nov-17-2017, 06:22 AM
Last Post: heiner55

Forum Jump:


Users browsing this thread: 1 Guest(s)