<jupyter_start><jupyter_text>Example 4th order Runge KuttaThe general form of the population growth differential equation$$ y^{'}=t-y, \ \ (0 \leq t \leq 4) $$with the initial condition$$y(0)=1,$$Has the exact soulation. $$ y= 2e^{-t}+t-1$$  Setting up Libraries<jupyter_code>import numpy as np
import math 

%matplotlib inline
import matplotlib.pyplot as plt # side-stepping mpl backend
import matplotlib.gridspec as gridspec # subplots
import warnings

warnings.filterwarnings("ignore")<jupyter_output><empty_output><jupyter_text>Defining the function$$f(t,y)=t-y$$<jupyter_code>def myfun_ty(t,y):
    return t-y<jupyter_output><empty_output><jupyter_text>Initial SetupDefining the step size $h$ from the interval range $a\leq t \leq b$ and number of steps $N$$$h=\frac{b-a}{h}.$$This gives the discrete time steps,$$t_{i}=t_0+ih,$$where $t_0=a$.<jupyter_code># Start and end of interval
b=4
a=0
# Step size
N=8
h=(b-a)/(N)
t=np.arange(a,b+h,h)<jupyter_output><empty_output><jupyter_text>Setting up the initial conditions of the equation$$w_0=IC$$<jupyter_code># Initial Condition
IC=1
w=np.zeros(N+1)
y=(IC+1)*np.exp(-t)+t-1#np.zeros(N+1)
w[0]=IC<jupyter_output><empty_output><jupyter_text>4th Order Runge Kutta $$k_1=f(t,y),$$$$k_2=f(t+\frac{h}{2},y+\frac{h}{2}k_2),$$$$k_3=f(t+\frac{h}{2},y+\frac{h}{2}k_2),$$$$k_4=f(t+\frac{h}{2},y+\frac{h}{2}k_3),$$$$w_{i+1}=w_{i}+\frac{h}{6}(k_1+2k_2+2k_3+k_4).$$<jupyter_code>for k in range (0,N):
    k1=myfun_ty(t[k],w[k])
    k2=myfun_ty(t[k]+h/2,w[k]+h/2*k1)
    k3=myfun_ty(t[k]+h/2,w[k]+h/2*k2)
    k4=myfun_ty(t[k]+h,w[k]+h*k3)
    w[k+1]=w[k]+h/6*(k1+2*k2+2*k3+k4)<jupyter_output><empty_output><jupyter_text>Plotting Results<jupyter_code>fig = plt.figure(figsize=(10,4))
# --- left hand plot
ax = fig.add_subplot(1,3,1)
plt.plot(t,w, '--',color='green')
#ax.legend(loc='best')
plt.title('Numerical Solution h=%s'%(h))

ax = fig.add_subplot(1,3,2)
plt.plot(t,y,color='black')
plt.title('Exact Solution ')

ax = fig.add_subplot(1,3,3)
plt.plot(t,y-w, 'o',color='red')
plt.title('Error')
# --- title, explanatory text and save
fig.suptitle(r"$y'=t-y,   y(0)=%s$"%(IC), fontsize=20)
plt.tight_layout()
plt.subplots_adjust(top=0.85)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.2164855072463768, 'fraction_numerical': 0.035778985507246376, 'mean_word_length': 7.304511278195489, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '21987', 'license': 'MIT', 'n_tokens_mistral': 1050, 'n_tokens_neox': 1011, 'n_words': 153, 'path': 'Chapter 03 - Runge Kutta/.ipynb_checkpoints/302_4th Order Runge Kutta-checkpoint.ipynb', 'repo_name': 'jjcrofts77/Numerical-Analysis-Python', 'size': '2208'}