It looks like it’s time for differential equations.
So, let’s say that you have a differential equation like the one below and you are striving trying to find an analytical solution. Chill out, maybe take a walk outside or ride your bike and calm down: sometimes an analytical solution does not exist. Some differential equations simply don’t have an analytical solution and might drive you mad trying to find it.
Fortunately, there is a method to find the answer you may need, or rather, an approximation of it. This approximation sometimes can be enough of a good answer.
While there are different methods to approximate a solution, I find Euler’s method quite easy to use and implement in Python. Furthermore, this method has just been explained by Sal from Khan Academy in a video on YouTube which is a great explanation in my opinion. You can find it here.
Here below is the differential equation we will be using:
and the solution (in this case it exists)
Here is the Python code algorithm. Note that the smaller the step (h), the better the approximation (although it may take longer).
# Euler's method for approximating differential equations | |
import math | |
import matplotlib.pyplot as plt | |
# Your differential equation. It should be in the form: dy/dx= f(t,y) | |
# Remember that f returns the value of the slope in that point | |
def f(t,y): | |
return 2-math.e**(-4*t)-2*y | |
def solution(t): | |
return 1+0.5*math.e**(-4*t)-0.5*math.e**(-2*t) | |
t0 = 0 | |
y0 = 1 | |
# Step size, the smaller the better, however it may take longer to compute | |
h = 0.005 | |
x = [t0] | |
y = [y0] | |
y2 = [y0] | |
errors = [] | |
while t0 < 5: | |
m = f(t0,y0) | |
y1 = y0 + h*m | |
t1 = t0+h | |
x.append(t1) | |
y.append(y1) | |
solut = solution(t1) | |
y2.append(solut) | |
error = abs(y1-solut)/y1*100 | |
errors.append(error) | |
print("Actual t","predicted y","Percentage error %",sep=" ") | |
print(t1,y1,error) | |
t0=t1 | |
y0=y1 | |
print("Mean of error:",sum(errors)/len(errors),"%",sep=" ") | |
plt.plot(x,y2,label="Function") | |
plt.plot(x,y,label="Approximation") | |
plt.legend(loc='upper right') | |
plt.title("Euler's method approximation, h="+str(h)) | |
plt.show() |
Here are some approximations using different values of h:
Hope this was interesting.
No comments:
Post a Comment