Modeling of Fundamental Electronic Circuits by The Euler Method Using The Python Programming Language
Modeling of Fundamental Electronic Circuits by The Euler Method Using The Python Programming Language
PAPER
Modeling of fundamental
electronic circuits by the
Euler method using the
Python programming
language
Ljubomir Gojković1, Stefan Malijević1
and Stevan Armaković2,1
1
High School ‘Jovan Jovanović Zmaj’, Zlatne Grede 4, 21000, Novi Sad, Serbia
2
University of Novi Sad, Faculty of Sciences, Department of Physics, Trg Dositeja
Obradovića 4, 21000, Novi Sad, Serbia
E-mail: stevan.armakovic@df.uns.ac.rs
Abstract
In this work three examples of textbook circuits (resistor-capacitor,
resistor-inductor and resistor-inductor-capacitor) have been modeled by
employing the Euler method for the approximate solution of differential
equations using algorithms implemented in the Python programming
language. The aim of this work was to demonstrate how simple, yet highly
effective, algorithms can be neatly implemented in one of the currently most
popular programming languages for scientific applications. At the same time,
the visualization of the results allows for a detailed introduction to the
properties of the circuits most frequently commented on in all the relevant
textbooks. Our code, as provided to the reader, includes detailed comments,
and can easily be modified to model other similar systems. Instructions on
how to prepare tasks for students have been also provided.
September 2020 2 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
Modeling of fundamental electronic circuits by the Euler method
September 2020 3 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
L Gojković et al
15. tf = 10 setting the final value of time to be 10 s. That
16. n = 21 means that we will have a graphical representation
17. dt = (tf-t0)/(n-1) of how I changes with time over 10 s. Of course,
18. print(''step size is: '', dt) the final value can be set to any other value, but for
19. the present values of the parameters, the graphical
20. t = np.linspace(t0,tf,n) representation will be the most suitable if the final
21. i = np.zeros(n) value of time is around 10 s.
22. We next define the number of steps we will
23. #Euler_1stODE solver have in the iteration procedure. For this purpose,
24. for z in range(0,n-1): in line 16 we set the value of n to be 101. In other
25. t[0] = t0 words, the interval between the starting and final
26. i[0] = i0 values of t (t0 and tf ) will be divided into n points.
27. i[z+1] = i[z] + dt∗ di_dt(i[z]) This means that we will have n − 1 sub-intervals
28. in the range between t0 and tf . Now it is possible
29. #Plotting section to define the value of the step, dt, that is used in
30. plt.title(''RL circuit'') the main equation of Euler’s algorithm.
31. plt.plot(t,i,label= '' approximation'') Before writing the main loop that will solve
32. plt.plot(t,i_ex(t),label= '' exact'') the differential equation, we have to define two
33. plt.legend(loc=’center right’) lists. The first list will contain the values of t,
34. plt.xlabel(''Time [s]'') which will be plotted using the x-axis of the graph-
35. plt.ylabel(''Current [A]'') ical representation. For this purpose, in line 20
36. plt.ylim(bottom=0) we used the linspace command, which divides the
37. plt.xlim(left=0) desired interval into n values.
38. plt.grid() The second list is the list that contains the
39. plt.show() values of i. We will initially set all of these val-
ues to zero, using the command zeros in line
In the first two lines we are importing the two 21, which generates the list with n members
Python packages—numpy and matplotlib. The and sets each member of that list to zero. Then,
former contains mathematical functions, while the using the loop that follows, we will be repla-
second package serves for plotting the results. In cing these values with the solution for each
lines four to eight, we are defining functions. In iteration.
lines four and five, we are defining in practical Now comes the main loop. We set our counter
terms the differential equation to be solved via z to iterate from zero to n − 1, in order to cover
the Euler method. In lines seven and eight, we are all of the sub-intervals in the interval between t0
defining the function which is the exact solution and tf . In line 25, we actually set the initial val-
of differential equation (1), so that we can com- ues of I and t in the corresponding lists (defined
pare the exact and approximate solutions. Notice in lines 20 and 21), by replacing the initial value
that the numpy package was used for defining the of those lists with I0 and t0 . Now comes the main
exponential function. In lines 10–12 we are defin- line of the algorithm, line 27, in which we imple-
ing the numerical values of the circuit compon- ment the equation in practical terms (6). Finally,
ents: V, R and L. the last 10 lines provide instructions to matplot-
One of the crucial initial steps in the applic- lib on how to present the acquired results. Line 31
ation of the Euler method is to define the initial instructs Python to plot the approximate results,
values. In terms of equation (1), this means that while line 32 instructs Python to plot the exact
we have to define the initial values for i and t. The results. In figure 1, we present the results of the
moment when the switch is closed is the moment code provided above for the two values of n = 21
when the whole process starts (t = 0), and at that and n = 101. The other parameters are: V = 50 V,
particular moment, I = 0. Therefore, the starting R = 2Ω and L = 3 H.
or initial values of these two parameters are zero, Of course, the accuracy of the presented code
as written in lines 13 and 14. In line 15 we are depends on the number of sub-intervals taken into
September 2020 4 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
Modeling of fundamental electronic circuits by the Euler method
Scheme 2. RC circuit.
September 2020 5 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
L Gojković et al
where R is the resistance of the resistor, i is the 28.
current intensity and C is the capacitance. The 29. #Plotting section
exact solution of differential equation (11) is the 30. plt.title(''RC circuit'')
following: 31. plt.plot(t,i,label= '' approximation'')
32. plt.plot(t,i_ex(t),label= '' exact'')
i = VR e− RC .
t
(12) 33. plt.legend(loc=’center right’)
34. plt.xlabel(''Time [s]'')
As in the previous case, expression (12) 35. plt.ylabel(''Current [A]'')
is frequently provided to students as-is, and its 36. plt.ylim(bottom=0)
exact derivation is beyond the scope of the high 37. plt.xlim(left=0)
school physics curriculum. Nevertheless, through 38. plt.grid()
an application of Euler’s method, equation (11) 39. plt.show()
can be approximated with a procedure identical to
the one presented in the previous chapter. Follow- This time we are not going to comment on
ing the same procedure presented in the previous each and every line of the code, because the code
chapter, we arrive at the following equation, to be itself is totally analogous to the previously presen-
implemented in Python code: ted code for the case of the RL circuit. Instead, we
( ) will emphasize the most important differences. Of
i [j + 1] = i [j] − ∆t · Ri[·jC] . (13) course, the equations defined at the start now cor-
respond to the RC circuit, different numerical val-
The Python code for the approximate solution ues for V and R are considered, and instead of L,
of (11) via the Euler method is: we now have C. The corresponding numerical val-
ues are V = 100 V, R = 20Ω and C = 0.03 F.
1. import numpy as np Probably the most important difference in
2. import matplotlib.pyplot as plt comparison with the previous code is related to
3. the initial value of the current. Instead of zero,
4. def di_dt(i): the initial value of the current is V/R, and the
5. return -(i)/(R∗ C) explanation for this value arises by analyzing the
6. RC circuit. Once the switch is closed, the cur-
7. def i_ex(t): rent starts flowing through the circuit and at the
8. return (V/R)∗ (np.exp(-t/(R∗ C))) very beginning, the voltage across the capacitor is
9. zero, and one can imagine that the whole circuit
10. V = 100 consists of the battery and R. Therefore, the max-
11. R = 20 imal and initial value of the current, according to
12. C = 0.03 Ohm’s law, is equal to V/R. However, as the time
13. i0 = V/R passes, the plates of the capacitor are charging
14. t0 = 0 until they are fully charged. Once the capacitor is
15. tf = 5 fully charged, the current stops passing through
16. n = 21 the circuit. Therefore, the initial value of time is
17. dt = (tf-t0)/(n-1) t = 0, while the initial value of current is i = V/R,
18. print(''step size: '', dt) and the final value of current is if = 0. We present
19. the results of the provided code in figure 2.
20. t = np.linspace(t0,tf,n) The solution of differential equation (8)
21. i = np.zeros(n) shows that the current is dropping exponentially
22. as time passes by. As in the case of the RL circuit,
23. #Euler_1stODE solver a rather low value of n = 21 generates the approx-
24. for z in range(0,n-1): imate result (blue colored line in figure 2(a))
25. t[0] = t0 which differs enough, in comparison to the exact
26. i[0] = i0 result, to be observable by students. The increase
27. i[z+1] = i[z] + dt∗ di_dt(i[z]) of n to 101 produces an approximate result, which
September 2020 6 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
Modeling of fundamental electronic circuits by the Euler method
Figure 2. I = f (t) for an RC circuit; a) n = 21 and b) where k1 and k2 are the roots of the auxiliary equa-
n = 101. tion corresponding to differential equation (14).
The auxiliary differential equation is:
almost completely coincides with the exact solu- Lk2 + Rk + C1 = 0. (16)
tion (figure 2(b)).
A brief inspection of the solution provided and it is roots are:
by (8) indicates that the current drop principally √ 2 4L √ 2 4L
R −C R −
depends on R · C. This is of course a great oppor- k1 = − 2L + 2L , k2 = − 2L − 2L C .
R R
September 2020 7 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
L Gojković et al
order differential equations is to transform it to 2. import matplotlib.pyplot as plt
a system of two first order differential equations. 3.
How is this done? We pick the first derivative and 4. R = 20
call it a new quantity. We then write the second 5. C = 0.002
order derivative with respect to the newly intro- 6. L = 20
duced quantity. Let us see how is that related to 7. t0 = 0
differential equation (14). We replace the di
dt with 8. tf = 10
some new quantity: 9. i0 = 2
10. n = 1001
di
dt = s. (18) 11. dt = (tf-t0)/(n-1)
12. print(''step size: '', dt)
With s introduced, the second order time 13.
derivative of i now becomes: 14. t = np.linspace(t0,tf,n)
2
d i ds (19) 15. i = np.zeros(n)
dt2 = dt . 16. s = np.zeros(n)
Taking into account equations (18) and (19), 17.
the differential equation (14) now can be trans- 18. #Euler_2ndODE solver
formed into the following system of two first order 19. for j in range(0,n-1):
differential equations: 20. t[0] = t0
21. i[0] = i0
di
dt = s, (20) 22. i[j+1] = i[j] + dt∗ (s[j]) #equation (15)
23. s[j+1] = s[j] - dt∗ (s[j])∗ (R/L) -
dt∗ (1/(L∗ C))∗ i[j+1] #equation (16)
dt + R · s + C = 0.
L ds 1 24.
(21)
25. plt.plot(t,i)
After a small rearrangement of (21), the sys- 26. plt.xlabel(''Time [s]'')
tem now becomes: 27. plt.ylabel(''Current [A]'')
di
28. plt.title(''RLC circuit'')
dt = s, (22) 29. plt.grid()
30. plt.show()
ds
dt = −s · RL − L1·C , (23) We are now going to comment the most
important parts of this code. In comparison with
and after applying the procedure described for the previous two code listings, in this code we
obtaining equations (6)–(8), the system of equa- will not be defining the functions directly at the
tions to be implemented in code becomes: beginning and we are not going to include exact
i [j + 1] = i [j] + ∆t · s [j] , (24) solutions, for the sake of simplicity. Instead, only
equations (24) and (25) will be defined in the main
loop. In the first 12 lines we have defined the
( ) ( ) numerical values of the parameters that are neces-
s [j + 1] = s [j] − ∆t · s [j] · RL − ∆t · L1·C .
sary for solving the equations. As in the previ-
(25)
ous two code listings, in lines 14 and 15 we have
Equations (24) and (25) are to be solved defined the values of t to be used for the calcu-
simultaneously, and because they are mutually lations and a list of values for i. So far, we have
dependent (s [j] is present in both of them), they generated a list of values for i, but we also must
are referred to as coupled equations. We provide generate a list of values for the newly introduced
below Python code for the solution of these equa- quantity s (in line 16), because we are solving two
tions: equations, practically speaking.
Now comes the main loop, which is com-
1. import numpy as np pletely analogous to the previous two listings,
September 2020 8 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
Modeling of fundamental electronic circuits by the Euler method
D = b2 − 4ac, (26)
D = R2 − 4 CL . (27)
In the most general case, D can be higher than Figure 4. Critically-damped RLC circuit (R = 200Ω,
zero, equal to zero or lower than zero. So, let us L = 20 Hand C = 0.002 F).
further define the values of L and C as the val-
ues from the code (20 H and 0.002 F), analyze the √
2. If D = 0 → R2 = 4 CL → R = 2 L
R = 200Ω
three general cases and deduce the critical values C
of R:
√ In this particular case, let us set the value of
1. If D > 0 → R2 > 4 CL → R > 2 CL → R > R to be precisely 200Ω. In such a case the ‘critic-
200Ω ally damped’ scenario is obtained, as presented in
figure 4.
Let us run our code with R taking a value This case can be interpreted in the following
significantly higher than 200Ω, for instance let way: i starts to drop, it is heading to equilibrium
us take a value of 500Ω.This value produces and trying to oscillate, but just as it arrives close to
the so-called ‘over-damped’ case, as presented in equilibrium, there is just enough damping to pre-
figure 3. vent it from going through equilibrium and oscil-
It can be seen that i starts to drop towards lating.
equilibrium and tries to oscillate, but very soon
after the initial moment, thanks to the very strong √
damping force, it is driven away from the equilib- 3. If D < 0 → R2 < 4 CL → R < 2 L
C →R<
rium position. 200Ω
September 2020 9 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
L Gojković et al
of the differential equations, based on the finite
difference approximation. Particular attention was
paid to the RLC circuit, since the modeling of
this circuit is based on a second order differ-
ential equation. The most important features of
the electronic circuits under consideration were
also covered methodologically. Therefore, in each
chapter we provided clear instructions on how to
prepare tasks for students.
The physical systems covered in this work
turned out to be very good examples for mod-
eling at the high-school physics level. From a
mathematical standpoint, the differential equa-
Figure 5. Under-damped RLC circuit (R = 20Ω, L = tions describing these circuits are at a suitable
20 Hand C = 0.002 F). level of difficulty for high school students with
an orientation towards the natural sciences. From
This is the most interesting case. Let us, a computational standpoint, the availability and
for example, set the value of R to 20Ω, thanks simplicity of the Python programming language is
to which we will obtain the so-called ‘under- perfect for these types of applications. This work
damped’ case, as presented in figure 5. also demonstrates how different skills (mathemat-
In the under-damped scenario, the damping ics and programming) can be applied for solving
force is not strong enough to prevent the i from of realistic physical problems.
oscillating. Therefore, i oscillates, however the
oscillations are damped after a certain amount
of time. Of course, the amount of time required Acknowledgments
to fully damp the oscillations increases with the The authors acknowledge the financial support of
lowering of R. Using the numerical values spe- the Ministry of Education, Science and Techno-
cified within figure 5, we can see that after around logical Development of the Republic of Serbia
10 s, i decreases from 2A to 0A. (Grant No. 451-03-68/2020-14/200125).
The specific features of RLC circuits demon-
strated in this chapter are ideal for problem ses-
sions with students. For the selected values of L ORCID iD
and C (or any other combination of two quantit- Stevan Armaković https://orcid.org/0000-
ies), students could be given a task to find the crit- 0002-8049-9969
ical values that would lead to the presented three
cases, by analyzing the corresponding discrimin- Received 14 April 2020, in final form 6 May 2020
ant. Accepted for publication 20 May 2020
https://doi.org/10.1088/1361-6552/ab94d5
4. Conclusions
Three textbook examples of electronic circuits References
have been modeled using the approximate method [1] Kürkçü Ö K, Aslan E and Sezer M 2017 A
numerical method for solving some model
for solving differential equations. The procedure problems arising in science and convergence
based on the famous Euler method was implemen- analysis based on residual function Appl.
ted in the Python programming language. All of Numer. Math. 121 134–48
the code is fully provided within this text and all [2] Langtangen H P, Barth T J and Griebel M 2008
of the program lines are explained in detail. Python Scripting for Computational Science
(Berlin: Springer)
Before analyzing the code written in Python, [3] Grus J 2019 Data Science from Scratch: First
we also demonstrated how to derive the expres- Principles with Python (Sebastopol, CA:
sions necessary for the approximate computations O’Reilly Media)
September 2020 10 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6
Modeling of fundamental electronic circuits by the Euler method
[4] Griffiths D F and Higham D J 2010 Euler’s [18] Oliphant T E 2006 A Guide to NumPy
method Numerical Methods for Ordinary (Charleston, SC: Trelgol Publishing)
Differential Equations: Initial Value [19] Hunter J D 2007 Matplotlib: a 2D graphics
Problems (London: Springer) environment Comput. Sci. Eng. 9 90–5
pp 19–31
[5] Kezerashvili R Y 2012 Teaching RC and RL
circuits using computer–supported Ljubomir Gojković finished ‘Jovan
experiments IERI Procedia 2 609–15 Jovanović Zmaj’ high school in Novi
[6] JoVE Science Education Database 2020 Physics Sad. He fell in love with physics
II RC/RL/LC Circuits (Cambridge, MA: from an early age and began his
JoVE) education by enrolling the class
[7] Kladovščikov L, Navickas R and Kiela K 2019 of students with special abilities in
Self-tuning system for multistandard active physics. His further plan is to study
RC filters Microelectron. J. 90 260–6 at the Faculty of Technical Sciences,
[8] Saslow W M 2002 Batteries, Kirchhoff’s rules, University of Novi Sad and specialize
and complex circuits In Electricity, in microcomputer electronics.
Magnetism, and Light ed W M Saslow (New
York: Academic) ch 8 pp 336–83
[9] van Drongelen W 2018 Introduction to filters: Stefan Malijević finished ‘Jovan
the RC-circuit In Signal Processing for Jovanović Zmaj’ high school in
Neuroscientists 2nd edn ed W van Drongelen Novi Sad, Serbia, class of students
(New York: Academic) ch 15 pp 307–14 with special abilities in physics. He
[10] Rawlins J C 2000 RL circuit analysis In Basic is interested in physics and plans
AC Circuits 2nd edn ed J C Rawlins to enroll physics studies at the
(Burlington: Newnes) ch 9 pp 303–34 Department of Physics, Faculty of
[11] Kumar K S 2008 Electric Circuits and Networks Science, University of Novi Sad.
(Noida: Pearson)
[12] Makarov S N, Ludwig R and Bitar S J 2016
Practical Electrical Engineering (Berlin:
Springer)
[13] Nilsson J W and Riedel S A 2015 Electric Stevan Armaković obtained his PhD
Circuits (Upper Saddle River, NJ: Pearson) at the Department of Physics, Faculty
[14] Chen W K 2004 The Electrical Engineering of Sciences, University of Novi
Handbook (Amsterdam: Elsevier) Sad, where he currently works as an
[15] Knopp T and Buzug T M 2012 Magnetic Assistant Professor. In 2019 he also
Particle Imaging: An Introduction to began teaching ‘Modeling in Physics’
Imaging Principles and Scanner at the ‘Jovan Jovanović Zmaj’ high
Instrumentation (Berlin: Springer) school in Novi Sad, for the students
[16] Annamaa A 2015 Introducing Thonny, a Python with special abilities in physics.
IDE for learning programming Proc. 15th So far he co-authored 106 papers
Koli Calling Conf. on Computing Education published in journals with impact
Research factor. His research activities include application of various
[17] Annamaa A 2015 Thonny, a Python IDE for computational methods in materials and pharmaceutical
learning programming Proc. 2015 ACM science. He is particularly focused to introducing the
Conf. on Innovation and Technology in high school and undergraduate students into the research
Computer Science Education activities. Personal web site: www.armakovic.com.
September 2020 11 P hy s . E d u c . 5 5 ( 2 0 2 0 ) 0 5 5 0 1 6