Trusted answers to developer questions

Zain Ali Babar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 $y(i+1)$ given the initial point $y(i)$. 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 $(x(i+1), (y(i+1))$. The image shows that the estimate, $y(i+1)$, which is marked in red, is very near to the actual value of $y(i+1)$, which lies on the curve and is marked in black.

$y_{(i+1)}=y_{i}+ k_{2}(h)$

$k_{1}=f(x_{i},y_{i})$

$k_{2}=f(x_{i}+\frac{h}{2}, y_{i}+k_{1}\frac{h}{2})$

- $k1$ is the overestimate and $k2$ is the underestimate.
- $h$ is the step-size.
- $x_{i}$ and $y_{i}$ are the initial conditions.

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()

Code demonstrates the midpoint function

The code above predicts the value of $y(i+1)$. 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.

RELATED TAGS

communitycreator

midpoint

python

CONTRIBUTOR

Zain Ali Babar

Grokking Modern System Design Interview for Engineers & Managers

Keep Exploring

Related Courses