In: Computer Science
Write a python code that uses the Euler Implicit method to approximate/plot the solutions to each of the following initial-value
I have writtend required comments along with the code please go through them thoroughly.
the euler implici formula is as follows:
y[n+1] = y[n] + h * (1/1+h) * (f(y,t[n+1]))
Please go through the formula ones the same will be reflected in the code.
import numpy as np # numpy library
import matplotlib.pyplot as plt # For Graph Plotting
def feval (funcName , *args): # given a function and its arguments it evaluates the value of that function
return eval (funcName) (*args)
def myfunction_1(t,y): # Declare of function 1
return -1.0*y*t + (4.0*t)/y
def myfunction_2(t,y): # Declaration of function 2
return 2.0*y + t*y
def euler_implicit(func, t_min, t_max, y_init, h): # implicit Euler method
N = int((t_max - t_min)/h) # Calculating the number of intervals between min and max time
t = np.linspace(t_min, t_max, N+1) # using numpy library we calcuate values added with h.
y = np.zeros(N+1) # for same interval as time period we have to calculate the y slope that dy/dt approximation
# set initial value
y[0] = y_init
for n in range(N): # in range interval
y_prime = (1/(1 + h)) * feval(func, t[n+1], y[n]) # formula for euler implicit is y[n+1] = y[n] + h * (1/1+h) * (f(y,t[n+1]))
y[n+1] = y[n] + h * y_prime
plt.plot(t,y) # plotting between time interval and y(t)
plt.xlabel('Time Interval(t)')
plt.ylabel('y(t)')
plt.title('Euler Implicit Method Approximation')
plt.show()
def main():
euler_implicit('myfunction_1', 0, 1, 1, 0.1)
euler_implicit('myfunction_2', 1, 3, -2, 0.2)
if __name__ == "__main__":
main()
Code Image Snippet:
Code
Output Image:
For any further doubts please leave a comment. you can run this code snippet as a script s well just copy paste the code in script and run it through command line.