The midpoint method is a type of second order Runge-Kutta method. It is used to solve ordinary differential equations with a given initial condition.
This method uses a tangent to approximate the next point given the initial point . This technique was named the midpoint method because it uses the tangent at the midpoint and then checks where the tangent cuts the vertical lines. The diagram below is an illustration of the midpoint method:
The tangent in black is drawn at the midpoint. The red secant is parallel to the tangent above and cuts the vertical line at . The image shows that the estimate, , which is marked in red, is very near to the actual value of , which lies on the curve and is marked in black.
The code below demonstrates the use of the midpoint method for a function.
import mathdef func(x,y):func = (3*math.exp(-x))-(0.4*y) #Example of ordinary differential equationreturn funcdef midpoint():##Initial Conditionsx = 0 #Independent variabley = 5##Integration Limitxi=0xf=3h=1.5 #stepsizeoriginal_ans=[5,4.37,2.76]print("Iteration",0)print("x:", x)print("estimated y:",y)print("original y:",original_ans[0])print("-------")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/2),y+(k1*h/2)) #K2y = y+(k2*h) #Midpoint formula to update yx = x+hprint("Iteration",i)print("x:", x)print("estimated y:",y)print("original y:",original_ans[i])print("--------------------")i=i+1def main():midpoint()main()
The code above predicts the value of . The number of iterations is found by dividing the interval by the step-size. For each iteration, the original value is printed with which to compare the estimate.