Heun’s method is a second-order Runge-Kutta method that is also known as the improved Euler Method. Heun’s method is a method to solve Ordinary Differential Equations, given an initial condition.
Heun’s method is built upon the Euler method. The Euler method uses the tangent to the curve at the initial point to check for the next estimate. The ideal point would be where the tangent cuts the curve. However, the assumption of small step size producing small errors doesn’t always hold. In the case of a larger step size or concave up curve, the Euler method fails to converge, as it overestimates the next term.
Heun’s method overcomes this problem by taking two tangents on both sides of the curve. One tangent overestimates while the other underestimates. Heun’s method then uses the Euler method to estimate the next term from both of these tangents.
Where:
import mathdef func(x,y):func = (3*math.exp(-x))-(0.4*y) #Example of ordinary differential equationreturn funcdef heun():##Initial Conditionsx = 0 #Independent variabley = 5##Integration Limitxi=0xf=3h=1.5 #stepsizeprint("Iteration",0)print("x:", x)print("y:",y)i=1n=(xf-xi)/h #number of iterationswhile i <= n: #This loop will run until the number of iterations are completedk1 = func(x,y) #K1k2 = func(x+h,y+(k1*h)) #K2y = y+((k1+k2)*(h/2)) #Heun's formula to update yx = x+h #updating xprint("Iteration",i)print("x:", x)print("y:",y)i=i+1def main():heun()main()