Model and simulate
Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.
Python cannot read a curve off a formula, so it marches time forward in 1 ms steps with the Runge-Kutta method. Push the mass with 1 N and it creeps to just 0.05 m. We want 1 m: we need a controller.
A first design
Add a proportional controller, Kp = 300, and feed the position back. Closing the loop is list arithmetic: T = CG / (1 + CG). Multiplying and adding the coefficient lists gives T(s) = 300 / (s² + 10s + 320).
Step the closed loop, then read numbers off the samples. It overshoots by 40.1 %, settles within 2 % after 0.77 s and ends at 0.94 m, not 1. Proportional control alone leaves a steady-state error.
A root finder gives the closed-loop poles: -5 ± j17.18. They sit far from the real axis, so the damping ratio is only 0.28. Light damping means a big overshoot.
Better designs
Derivative action (Kd = 10) pushes against fast motion. The poles move to -10 ± j14.83, the overshoot falls to 15.3 % and the loop settles in 0.29 s. It still ends at 0.94 m.
Integral action adds up the error over time and keeps pushing until it is zero. With Kp = 350, Ki = 300 and Kd = 50 the output heads for exactly 1 m, with no overshoot, settling in 0.83 s.
Automate and check
Now Python does the trying. A for loop steps Kd from 0 to 80 and keeps the fastest design with under 5 % overshoot. It picks Kd = 20: 4.1 % overshoot, settled in 0.73 s, faster than Kd = 50.
The python-control library does the same jobs with tf, feedback and step_info. It reports 4.1 % and 0.73 s for the winner, matching our code. Give it the time grid: its own default stopped one loop at 0.13 s.
Every design went round one loop: model, simulate, measure, change the gains. Python makes each lap take milliseconds, so you can try many controllers, then check the winner with a trusted library and on the real machine.
The Python so far
# step 1/10 · plant # about: Mass-spring-damper G(s), Python script # a transfer function is two lists of coefficients # G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20 G = [1], [1, 10, 20] print(G[0][-1] / G[1][-1]) # 0.05
step() writes T(s) in controllable canonical form (one first-order equation per power of s) and integrates it with the classical fourth-order Runge-Kutta method. With 1 ms steps the result matches python-control to every digit shown. The mass-spring-damper and the P, PD and PID gains are the worked example of the PID tutorial in the Control Tutorials for MATLAB (University of Michigan and Carnegie Mellon). Here every curve and number is recomputed in plain Python.