예제 #1
0
# %%
import context
from numlabs.lab4.lab4_functions import initinter41, eulerinter41, midpointinter41
import numpy as np
from matplotlib import pyplot as plt

initialVals = {
    'yinitial': 1,
    't_beg': 0.,
    't_end': 1.,
    'dt': 0.25,
    'c1': -1.,
    'c2': 1.,
    'c3': 1.
}
coeff = initinter41(initialVals)
timeVec = np.arange(coeff.t_beg, coeff.t_end, coeff.dt)
nsteps = len(timeVec)
ye = []
ym = []
y = coeff.yinitial
ye.append(coeff.yinitial)
ym.append(coeff.yinitial)
for i in np.arange(1, nsteps):
    ynew = eulerinter41(coeff, y, timeVec[i - 1])
    ye.append(ynew)
    ynew = midpointinter41(coeff, y, timeVec[i - 1])
    ym.append(ynew)
    y = ynew
analytic = timeVec + np.exp(-timeVec)
theFig, theAx = plt.subplots(1, 1)
#%matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
from numlabs.lab4.lab4_functions import initinter41, derivsinter41, midpointinter41

##### Write a function that computes the solution using Heun's method.
def heun(coeff, y, theTime):
    k1 = coeff.dt * derivsinter41(coeff,y,theTime)
    k2 = coeff.dt * derivsinter41(coeff,y + (2.0/3.0 * k1), theTime + (2.0/3.0)*coeff.dt)
    y = y + (1.0/4.0) * (k1 + (3.0 * k2))
    return y
                                        
##### Prepare for example eq:test.
initialVals={'yinitial': 0,'t_beg':0.,'t_end':1.,'dt':0.05,'c1':-1.,'c2':1.,'c3':1.}
coeff = initinter41(initialVals)
timeVec=np.arange(coeff.t_beg,coeff.t_end,coeff.dt)
nsteps=len(timeVec)

##### Set up lists for approximated values (m=midpoint, h=heun).
ym=[]
yh=[]
y=coeff.yinitial
ym.append(coeff.yinitial)
yh.append(coeff.yinitial)

##### Obtain approximated y values.
for i in np.arange(1,nsteps):
    ynew=midpointinter41(coeff,y,timeVec[i-1])
    ym.append(ynew)
    ynew=heun(coeff,y,timeVec[i-1])