0

Hi I want to plot a graph using the maximum values of I with respect to changes in variable r.

I'm using the Euler Method solution for an DE with my code being:

import numpy as np
from matplotlib import pyplot as plt 

B=0.001
r=0.06
n=101
dt=1
t0=0
tf=10

t = np.linspace(t0,tf,n)
S = np.zeros([n])
I = np.zeros([n])

S[0]=199
I[0]=1

for i in range(1,n):
 S[i] = S[i-1] + (- B * (S[i-1]) )* I[i-1] * dt
 I[i] = I[i-1] + (I[i-1] * (B * S[i-1] - r)) * dt

This would plot against variable t in the x-axis, with r being constant

But when I tried coding for a plot of I against r, by changing r into a variable, the values I get from print() is not equal to when I manually change the value of constant r(like above)

So I tried using np.max and r=np.linspace but I'm not getting the expected plots

import numpy as np
from matplotlib import pyplot as plt 

B=0.001
n=101
dt=1
t0=0
tf=10

t = np.linspace(t0,tf,n)
r = np.linspace(0.01,0.5,n)
S = np.zeros([n])
I = np.zeros([n])

S[0]=199
I[0]=1

for i in range(1,n):
 r[i] = r[i]
 S[i] = S[i-1] + (- B * (S[i-1]) )* I[i-1] * dt
 I[i] = I[i-1] + (I[i-1] * (B * S[i-1] - r[i])) * dt
Imax=np.max(I)
Imax2=np.array(Imax)

plt.plot(r,Imax2)

If I didn't use r=linspace I would get the size-1 array error in my I[i] line. Any ideas how do I get maximum value of I vs r?

1
  • Welcome to StackOverflow! I tried to run your code, but it is very buggy. First, tf and t0 aren't defined, and the for loop is on j while the content of the loop uses i indexing (undefined). Finally, the I array is always 1D. Could you make sure to run your code before posting? Commented Sep 28, 2020 at 7:46

1 Answer 1

0

Use the numpy function maximum for elementwise max.

The np.max function reduces the array to float (if no axis is specified).

I edited your code to allow it to run:

import numpy as np
from matplotlib import pyplot as plt 

B=0.001
n=101
dt=1
t0 = 0 # inferred not in the actual code
tf = 10 # inferred not in the actual code
t = np.linspace(t0,tf,n)
r = np.linspace(0.01,0.5,n)
S = np.zeros([n])
I = np.zeros([n])

S[0]=199
I[0]=1
# error with index, changed to i
for i in range(1,n):
 r[i] = r[i]
 S[i] = S[i-1] + (- B * (S[i-1]) )* I[i-1] * dt
 I[i] = I[i-1] + (I[i-1] * (B * S[i-1] - r[i])) * dt
# get max of I and S element wise
Imax=np.maximum(S, I)

plt.plot(r,Imax)
Sign up to request clarification or add additional context in comments.

Comments

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.