Modified Euler
Modified Euler¶
A first order diffarential equation can be written as It is given at , . So the next value of i.e, is given by
Now the integral can be solved in many ways numerically. What we do for Euler method is that, . But we can modify it better way. That is
You may recognize it is the Trapezoidal method for numerical integration( is spacing between and ). But how can we put in without knowing it? Where predict and correct concept/method come into picture. Crack is that you going to compute using Euler method and will put it into . Then we can compute new(rather good ) .
Predict: Use Euler method for first . i.e,
Correct: After computing from put it in ,
It is recurssion kind of problem so ultimate equation becomes,
is something I think it is the main culprit for accuracy.
import matplotlib.pyplot as plt
import numpy as np
def ModifiedEuler(xi, yi, h, xf, f, err):
xx, yy = [xi], [yi]
while (xf - xi) > 0:
#Predict
y_ = yi + h*f(xi, yi)
diff = 100
while diff > err:
#Correct
y = yi + 0.5*h*(f(xi, yi) + f(xi+h, y_))
diff = abs(y - y_)
y_ = y
yi = y
xi += h
xx.append(xi)
yy.append(yi)
return xx, yy
def Euler(xi, yi, h, xf, f):
xx, yy = [xi], [yi]
while(xf > xi):
yi += h*f(xi, yi)
xi += h
xx.append(xi)
yy.append(yi)
return xx, yy
Problem 1:¶
Solve the diffarential equation: with initial condtion . Solution will be . Both Euler and modified Euler. Take .
xi = 0; yi = 2; h = 0.5; xf = 3
def f(x, y): return -y + x + 2 #Diffarential equation
xxE, yyE = Euler(xi, yi, h, xf, f)
xxM, yyM = ModifiedEuler(xi, yi, h, xf, f, 0.1)
#Exact Solution
x = np.linspace(xi, xf, 100)
y = np.exp(-x) + x + 1
#Plotting
plt.figure(figsize = (12, 6))
plt.plot(xxE, yyE, "-go", label = "Euler")
plt.plot(xxM, yyM, "-ro", label = "Modified Euler")
plt.plot(x, y, label = "Exact")
plt.legend(loc = 'best')
plt.show()
You can see how powerful modified Euler is..
Comments
Post a Comment