<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Marat Kopytjuk on Medium]]></title>
        <description><![CDATA[Stories by Marat Kopytjuk on Medium]]></description>
        <link>https://medium.com/@kopytjuk?source=rss-891434466d3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*r5SSqdC1wA59diQzlTj2Ng.jpeg</url>
            <title>Stories by Marat Kopytjuk on Medium</title>
            <link>https://medium.com/@kopytjuk?source=rss-891434466d3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:59:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kopytjuk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From C to machine code — demystifying CPU mechanics]]></title>
            <link>https://medium.com/@kopytjuk/from-c-to-machine-code-demystifying-cpu-mechanics-e5d4cf967e8?source=rss-891434466d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5d4cf967e8</guid>
            <category><![CDATA[circuit]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[assembly]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Marat Kopytjuk]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 11:38:07 GMT</pubDate>
            <atom:updated>2019-12-05T11:38:07.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JiW2-rJrIzjBveWX" /><figcaption>Photo by <a href="https://unsplash.com/@yogeshp?utm_source=medium&amp;utm_medium=referral">Yogesh Phuyal</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wondered how your computer interprets human written (C-) code, compiles it to machine code and executes the operation you just programmed? For me those internal mechanics were a “miracle” for a long time — you hit compile, wait several seconds and voilà, your application runs!</p><p>Code in interpreted languages like Python or JavaScript, can be executed immediately, without any intermediate compilation, almost on any arbitrary operating system of your choice.</p><p>But what happens underneath? This article thrives to give you some deeper insight in compilers, computer architectures, assembly language and the mysterious machine code. After reading the article you will feel more comfortable using compilers and talking about machine code, instruction sets and architecture features.</p><h3>Prerequisites</h3><p>If you want to follow this article and reproduce the steps I do, install the <a href="http://sdcc.sourceforge.net/">SDCC </a>compiler suite for <a href="https://en.wikipedia.org/wiki/Intel_MCS-51">Intel MCS51</a>-like microcontrollers (e.g. 8051). In order to call the sdcc command from your shell, add the installation path to your PATH environment variable.</p><p>For writing code, you can use any plain text editor of your choice. In order to compile the program into the build folder run sdcc main.c -o ./build/.</p><p>You can execute the compiled code (.ihx) in the <a href="https://www.edsim51.com/">EdSim51</a> simulator. The Java-based tool emulates a 8051-like virtual CPU so you can go step for step over your instructions and observe the behavior of different registers. Furthermore there are some peripherals, like 7-segment displays if you want to write some fancy assembly programs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIlUGL3tYTKLetDhJqOZlg.png" /><figcaption>EdSim51</figcaption></figure><p>In this article I will frequently refer to the original <a href="http://eia.udg.es/~gomis/all8051.pdf">MCS51 datasheet</a>, don’t hesitate to download the PDF file!</p><p>Now we are prepared for our journey, grab your coffee and let’s go!</p><h3>Why 8051?</h3><p>MCS81 family was developed by <a href="https://en.wikipedia.org/wiki/Intel">Intel</a> in 1980 for use in embedded systems like vending machines or electric windows in your car. It is a lightweight 8-bit processor — 8-bit refers to the capacity of the arithmetic logical unit (ALU). Additionally, 8051 has various features like serial interface (UART), multiple timers, interrupts and the ability to connect to an external (outside the chip) data and code memory. For a more in-depth description, click <a href="https://en.wikipedia.org/wiki/Intel_MCS-51#Important_features_and_applications">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aFpVg6mTHfrD6Pe1XCMmQ.jpeg" /><figcaption>Intel P8051, Source: Wikipedia</figcaption></figure><p>The second reason for selecting MCS51 is that the family’s architecture not as complex as modern CPUs with their multi-level caching and <a href="https://en.wikipedia.org/wiki/Instruction_pipelining">pipelining </a>mechanisms. Understanding 8051 execution model will provide you at least a high level overview how modern CPUs work internally — it is a fascinating world connecting human logic written in a high level language with electrical nanometer-scale circuits.</p><p>Below you see the high level architecture of the MCS51 (screenshot from that datasheet):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoJeeO6RIOFb7CmXSCcggQ.png" /></figure><p>A highly important concept is the concept of different memory types. In the 8051 we have the <strong>4KB ROM block (code memory)</strong> and <strong>128 Bytes RAM (data memory)</strong>. The former stores your application code as a sequence of bytes — the latter is used for variables defined in your code, e.g. intermediate results of a complicated calculation.</p><p>(Modern CPUs follow the principle where both code and data can be stored in a single location, e.g. RAM or cache, see <a href="https://en.wikipedia.org/wiki/Modified_Harvard_architecture">here</a>, but for now we separate both worlds)</p><p>In a nutshell: the CPU sequentially reads the code memory (also called program memory) and executes different instructions like addition, data copy or bit shifting. The results are saved to RAM registers for further processing.</p><p>Let’s take a closer look how a fundamental add instruction is represented in code memory. A very common operation is to take a value from a particular address in data memory and add a second value to it. We will describe this process in assembly <a href="https://en.wikipedia.org/wiki/Assembly_language">language</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af1f6cd887677e8ff7a62ec80e13dd61/href">https://medium.com/media/af1f6cd887677e8ff7a62ec80e13dd61/href</a></iframe><p>First mov instruction copies a single byte from the data address _P1=0x90 to the accumulator, which is a special register within the CPU where all calculations take place. The consecutive add instruction adds a hexadecimal (negative) number 0xFB to the accumulator. The result is again copied from the accumulator to the RAM. The destination is r7 (register 7), which is a “special” memory location in RAM. Instructions involving registers take only half of the code memory space compared to similar instructions involving other arbitrary addresses in internal RAM. I.e. add A, r7 takes only 1 byte in ROM, whereas add A, 0xA7 needs 2.</p><p>If efficiency is your holy grail and the code space is limited, you think about that too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*kLw4Tk2F8Ad78RyjdqlN5w.png" /><figcaption>instruction codes for 8051</figcaption></figure><p>Let’s decompose the three lines of assembly code from basic.asm snippet into machine code which a 8051 can interpret.</p><p>The table of available instructions can be found on page 2–21 in the <a href="http://eia.udg.es/~gomis/all8051.pdf">MCS51 datasheet</a> (table on the left).</p><p>The mov A, addr instruction has the instruction code (or opcode)E5 and takes 2 bytes in the code memory.</p><p>The add command is 2 byte long and has the opcode 24 .</p><p>The last mov is a quick and short (1 byte) operation with opcode FF.</p><p>Let’s translate the sequence of commands we just wrote into sequence of bytes in program memory: E59024FBFF or if you wish a even less readable binary 1110010110010000001001001111101111111111 .</p><p>You will find this sequence somewhere in the program memory of the CPU.</p><p>That was tough! Give your brain some minutes of rest to digest. Instructions and operands of those instructions (like target and destination addresses) are located in program memory. In EdSim51 you can toggle between data and program memory by clicking on the memory button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*oLrqp2vRdL0Z3fgCd1BUbQ.png" /><figcaption>3-line snippet — code memory in EdSim51</figcaption></figure><h3>Level up!</h3><p>Writing assembly code is tough, even simple for-loops are a challenge to program them fail-safe and efficient. Efficiency here means taking the minimal amount of CPU cycles and memory for accomplishing an arbitrary task and that’s why higher-level languages like C exist — to make our life easier.</p><p>For the sake of the example we will use following dummy code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a472140d84dbec743a5677316c5dd3f/href">https://medium.com/media/1a472140d84dbec743a5677316c5dd3f/href</a></iframe><p>We read the value at the port P1, subtract a 5 and assign the result back to P1. We do that 3 times in a loop before the program quits.</p><p>Running sdcc addition.c -o ./build/ in the terminal leads to a creation of multiple files within the build folder. In this tutorial we take a look at addition.asm and addition.ihx. The .asm file is the compiler’s “translation” from C to assembly operations. Let’s take a look what the compiler proposed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a057b9d27a1180f6030c67fb668108b/href">https://medium.com/media/5a057b9d27a1180f6030c67fb668108b/href</a></iframe><p>The logic within the for-loop is implemented in lines 27–29:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9aa27008f5c1ab7334724a31e09c209/href">https://medium.com/media/a9aa27008f5c1ab7334724a31e09c209/href</a></iframe><p>Instead of using the subb subtract operation - the compiler &quot;misused&quot; the add operation and exploited the negative number representation implemented in most CPU architectures. Since <a href="https://en.wikipedia.org/wiki/Two%27s_complement">Two&#39;s complement</a> is used, the compiler can just rewrite x = x - 5 to x = -5 + x or x = 0xFB + x.</p><p>Since those three instructions shown above are located in code memory one after the other, we are able to translate them into machine code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fb86327b11a6356366ca665d66a3f82/href">https://medium.com/media/3fb86327b11a6356366ca665d66a3f82/href</a></iframe><p>This instruction sequence has to be placed somewhere in the ROM. Let’s open the addition.ihx file (which describes program data flashed to ROM) and find the sequence E59024FBF590 in the line 4:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d1e018021e2b3c2ff0808ad8bfc757/href">https://medium.com/media/48d1e018021e2b3c2ff0808ad8bfc757/href</a></iframe><p>The compiler translates our C code into an interpretable byte-stream saved to (code-) memory / ROM. The CPU parses the byte sequence and executes the desired operation. Here you also can find the reason why code compiled on Windows can both run on AMD and Intel CPUs — even if the internal electrical circuit architecture of those CPUs is different — the instructions (like mov), their operation codes and their functionality are the same.</p><p>Processors which support same operation codes share a common <em>instruction set</em> (like x86 with AMD and Intel for PCs). In comparison to 8051, modern CPUs share code and data memory in one location (e.g. RAM). Since data and code are interchangeable, some security issues arise. You could potentially execute harmful code disguised as application data — the only requirement is to know some internals (like OS, hardware) about your target system.</p><h3><strong>Down to the silicon!</strong></h3><p>Now we’ll take a step further and observe what happens on the CPU after we flashed our machine code to the program memory and pressed the reset button (causing a rising edge at RST pin).</p><p>The program counter (PC) will parse the first instruction stored in program memory (at the address 0x00). If E590 is the first command, the control unit will copy the content of port 1 (accessible at address 0x90) to the accumulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5C2hKzUZ8SSHNGiNX1-tw.png" /><figcaption>Parsing and executing mov a, 0x90 instruction, high level overview</figcaption></figure><p>The same process in little more depth:</p><ol><li>After reset, the program counter (PC) is set to 0x00</li><li>Apply the value of PC to the program address register (PAR). The PAR reveals the byte stored at 0x00 in program memory to the address bus.</li><li>Control unit stores the instruction code in instruction register.</li><li>Now the control unit is aware that for parsing the E5 instruction it needs an additional byte from program memory. The next byte in ROM is 90.</li><li>Move the content of 0x90 to the accumulator.</li></ol><p>The mapping “instruction-code → particular action” is implemented in hardware as a special circuit within the timing-and-control unit. It sets the right bits to access memory or execute a particular operation using the ALU module.</p><h3>Roundup</h3><p>Coding can be fun and it’s great to be able to write applications in Python or C without thinking about the hardware specifics. Imagine you would have to rewrite your logic in CPU specific instructions! Luckily nowadays, given the target compiler, you can run any arbitrary C code on various CPU architectures or manufacturers and standardization of the instruction sets (like x86 or <a href="https://de.wikipedia.org/wiki/RISC-V">RISC-V</a>) allows to distribute binaries across different devices.</p><p>I hope you have learned something new. Even if you don’t need this knowledge in your daily (coding) life, same as I don’t, it is sometimes useful to understand what happens underneath your keyboard.</p><h3>Special thanks</h3><p>Thanks to Anna F. for improving my English skills and reviewing my text. Also big thanks to <a href="https://github.com/herzog-ch">Christian H.</a> for his technical review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5d4cf967e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On simulating non-linear dynamic systems with Python or how to gain insights without using ML]]></title>
            <link>https://medium.com/data-science/on-simulating-non-linear-dynamic-systems-with-python-or-how-to-gain-insights-without-using-ml-353eebf8dcc3?source=rss-891434466d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/353eebf8dcc3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[scipy]]></category>
            <category><![CDATA[physics]]></category>
            <category><![CDATA[control-theory]]></category>
            <dc:creator><![CDATA[Marat Kopytjuk]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 19:06:46 GMT</pubDate>
            <atom:updated>2019-11-11T04:15:06.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6VvBt7LKm-To8xmo3ZAJQ.jpeg" /></figure><p>Machine Learning is everywhere. You hear about groundbreaking advances in language processing, computer vision or reinforcement learning everyday. Surprisingly, there are only few prominent examples for applying machine learning as core element in safety critical systems inside the engineering domain. Sure, Autonomous Driving (AD) stack heavily depends on Deep Learning algorithms for perception using radar, LIDAR and video as input, though the control part is still managed by methods developed over centuries in system theory and control engineering.</p><p>Reinforcement learning tries to solve the problem of controlling complex systems, but training agents requires thousands of epochs of trial-and-error (exploration/exploitation) in the target environment (i.e. in the AD example: real traffic with real vehicles)—which can be expensive or even dangerous. Alternatively, you could have a sufficiently accurate physical simulation of your environment, which you could use to train the baseline of your agent and later, after you reached a certain threshold with its performance, deploy the agent into real environment to transfer and adjust its knowledge. Physical models often simplify our non-linear real world in order to allow (numerical) calculations. RL agents will adjust their internal non-linear state-value or state-action function to those specific situations and achieve a superior performance as compared to traditional control methods.</p><p>This article tries to be a motivation for you to take a closer look on concepts introduced in control theory and apply them in your daily life for understanding things, playing around with parameters and observing the behavior of your system to changes you introduce. Or you could use this knowledge to build simulation environments as a training camp for your sophisticated, neural network based RL-agents.</p><h3>Audience</h3><p>I wrote this article for everyone interested in applying machine learning algorithms on real-world engineering problems. You should have some basic knowledge in maths, physics, mechanical and electrical engineering. Since we use Python for solving the ordinary differential equations (ODE) you should know about creating, manipulating and plotting NumPy arrays.</p><p>This article could be also interesting for you if you used MATLAB during your studies and now consider to switch to Python due to save costs or to use a larger ML/DL stack.</p><h3>Our System</h3><p>In this article we will develop a simple elevator model which consists of two main parts: the DC-motor armature (electrical part) on the left and the mechanical structure on the right side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTf_V8DZ4ZVUcSh5a2Rn1g.png" /></figure><p>In the next two sections we will derive mathematical descriptions for both parts. Afterwards we’ll combine all equations into a single state-space model describing our full system. Stay tuned!</p><h4>(Brushed) DC-motor</h4><p>Mathematically a brushed DC motor is an electrical network which consists of a motor resistance <strong>R </strong>(resistance of the coil winding), inductance <strong>L</strong> and electromotive force <strong>Ui</strong> which is coupled with rotational speed <strong>n</strong>. The torque <strong>M </strong>is proportional to the current<strong> i(t)</strong>. The torque <strong>M</strong> divided by the radius of the shaft <strong>r</strong> leads to a driving force <strong>F</strong> which pulls the cabin up. Formally we have following relations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*qnDEMJLODf6WIKCf.png" /><figcaption>Equations of the electromechanical side</figcaption></figure><p>First equation is the formal relationship between the current <strong>i(t)</strong> and the driving torque <strong>M</strong>. The torque is proportional to the motor’s characteristic <strong>k</strong>.</p><p>The second equation shows the linear relationship between the electromotive force voltage <strong>Ui</strong> and the rotational speed <strong>n(t)</strong>. The factor between both is again, the motor parameter <strong>k</strong>.</p><p>The third equation describes mechanical dynamics of the motor (<a href="https://en.wikipedia.org/wiki/Mechanical_equilibrium">mechanical equilibrium</a>). The inertia of the shaft is set to zero since its influence is negligible to the gravitational and inertia forces of the elevator cabin. Note that leaving out the rotational inertia leads to our first approximation where we potentially lose accuracy!</p><p>The last equation is a realization of <a href="https://en.wikipedia.org/wiki/Kirchhoff%27s_circuit_laws#Kirchhoff&#39;s_voltage_law">Kirchhoff’s voltage law</a> which is an important link between the force <strong>F </strong>(over<strong> i(t)</strong>) and the input voltage <strong>u</strong>. The input voltage is the input signal of our system, it controls the elevator’s height <strong>x.</strong></p><p>There is a second more major inaccuracy in our model — the third equation implies that we have a constant <strong>r</strong> which is not true in the real world, since the radius of the shaft will increase by rope thickness with each additional revolution. But in order to keep the equations simple, we will assume that the rope thickness is negligible relative to the radius of the shaft itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*hwSVlYk2YAmojyaJ.jpg" /><figcaption>Visual example of the radius increase issue. Image source: <a href="https://picclick.fr/36mm-Naturelle-Coton-Bannister-Rampe-%C3%89scalier-Corde-X-303031999809.html">https://picclick.fr/36mm-Naturelle-Coton-Bannister-Rampe-%C3%89scalier-Corde-X-303031999809.html</a></figcaption></figure><h4>Mechanical structure</h4><p>To realize a relation from <strong>F</strong> to the height <strong>x</strong> we will again use the law of <a href="https://en.wikipedia.org/wiki/Mechanical_equilibrium">mechanical equilibrium</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/0*1SaBtP62woo3AvPH.png" /><figcaption>Driving force F_A is a sum of inertia and gravitation</figcaption></figure><p>Gravitational force pulls our cabin down where the driving force tries to pull it up. The inertia force proportional to the vertical acceleration of our elevator.</p><p>The connection between the vertical velocity <strong>v</strong> of the cabin and the rotational speed <strong>n(t)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*XSNCnrHokwS9Oabb.png" /></figure><h3>Setting out for state-space</h3><p>In order to simulate the ODEs above we will combine them in a <a href="https://en.wikipedia.org/wiki/State-space_representation">state-space</a> representation. A state <strong>s </strong>is a <strong>n</strong>-dimensional vector (n := number of states) which describes the whole system at each point in time, i.e. we can derive all other variables (included the output variable) given <strong>s</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*5VLkRfLl3wnz_ePUAs4WLQ.png" /><figcaption>State-space representation</figcaption></figure><p>The representation consists of two equations. In the first equation the derivative of <strong>s</strong> depends on the state itself and an input vector <strong>u</strong> (in our case it is a scalar, since we have a single input, the voltage of the DC-motor). The second equation shows the output behavior of our system which of course depends on the state of the system and again the input <strong>u</strong>.</p><p>Let’s set up the representation. There are several methods to derive the representation, we will use the simplest one (imho!), since it does not require any knowledge about Laplace-based transfer functions. <strong>Our state variables will be variables which lead to energy increase or decrease in our system.</strong></p><p>A good rule of thumb is to select variables which cannot jump between different levels. Take <strong>x(t)</strong> as an example. The lift cabin cannot change its height from 0 to 10m within an infinitely short time period, since this process would also require an infinite amount of electrical power. As you probably remember from your physics lesson the formula for calculating potential energy is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/0*_q-Vs5r9HVyEGC7r.png" /><figcaption>m: mass of the object, g: gravitational acceleration, h: relative height to 0 potential</figcaption></figure><p>The second state variable is the vertical velocity of the cabin. The speed also cannot jump from 0 to 10m/s. The reason is the same as above, signals which indicate energy in our system would require infinite power for sudden changes. Additionally there is also a formula for kinetic energy from your physics lesson:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/0*GSfyeM6sRxqemi9Z.png" /><figcaption>v: vertical velocity</figcaption></figure><p>The third state is not that obvious. Until now our energy variables x and v only described the mechanical part. In the electrical circuit we have the next energy storage — inductance <strong>L</strong>. You cannot change the voltage over the inductance as you can do that with a simple resistor. Thus we introduce <strong>i(t)</strong> as our third state variable. Here, the equation for magnetic energy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/0*zaYivHZ51gK1GHAV.png" /></figure><p>All other variables in the mechanical and electrical parts introduced above are linearly dependent on the selected state variables. Let’s rearrange the equations, so that on the left side we only have the first derivative of state variable and on the right side everything else (without derivatives).</p><p>We will go through the process with the variable <strong>i(t)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*EKFUEdchJtO7zPP2.png" /><figcaption>The derivative of i(t) only depends on the input u(t), the current i(t) and velocity v(t), which are input or state variables respectively.</figcaption></figure><p>With a similar approach we get the equations for <strong>x</strong> and <strong>v. </strong>All together we have our state-space equation system (1st order ODE):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/0*Juu1Xn2kM5HidJSz.png" /></figure><p>In matrix form (the general form) — the TL;DR version of this large section:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*mDfV7gTtBztPwPb7.png" /><figcaption>State-space representation of our elevator example. Note, that because of gravitation our input vector has two elements, the input voltage <strong>u(t)</strong> and a constant 1 which is multiplied with <strong>g</strong>.</figcaption></figure><p>In other words we have now our state-space matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*ZnHjx66ZCLMKkTrG.png" /><figcaption>A: state-matrix, B: input-matrix, C: output-matrix, D: feedforward-matrix</figcaption></figure><h3>Model in action (with SciPy)</h3><p>First we import few packages used in this tutorial and initialize system’s parameters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6cec74c50782a9f9651b9b5f98f132d/href">https://medium.com/media/b6cec74c50782a9f9651b9b5f98f132d/href</a></iframe><p>Let’s define our state-space representation matrices and initialize the <em>StateSpace</em> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d78cdfac70c9df7bdc84490a72c64f/href">https://medium.com/media/69d78cdfac70c9df7bdc84490a72c64f/href</a></iframe><p>For our first simulation we want to observe what would happen if we short the input voltage <strong>u(t)</strong> (i.e. we set it to 0). We define the input vector and simulate with <em>lsim</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c588e4d25eb7f2f968a17f97ba2362b5/href">https://medium.com/media/c588e4d25eb7f2f968a17f97ba2362b5/href</a></iframe><p>Since the signal of our interest (the height <strong>x</strong>) is the equal to the first state variable, we will use the first state variable from now on in following visualizations.</p><p>Let’s observe how our system behaves, we plot the 3-dimensional state vector over time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LM8bDgXvOnLnttx08KSi5g.png" /></figure><p>Ok, apparently the gravitation pulls the lift cabin down (i.e. <strong>x(t)</strong> is decreasing) — as expected. Interestingly, the way down is not smooth, the cabin oscillates. The reason for that abnormal behavior is that the DC-motor is not only a driving motor, it is also a generator. The potential energy of the cabin is converted into electrical energy which itself converted in heat on the resistor <strong>R</strong> (P = RI² = (25A)²*2 Ω = 1250W).</p><p>Let’s explore what happens when we vary the magnitude of the input function u(t). We simulate for different magnitudes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUepa_YEleGkq-fNf88_1w.png" /></figure><p>Looking at the first two seconds we observe that the cabin will fall by approximate 25cm independent of the input voltage. Furthermore we can “control” cabin’s velocity and acceleration.</p><p>In the next example we will vary the shaft radius <strong>r</strong> and plot the system’s step response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeM8cY4368SwAy5x6LbXOA.png" /></figure><p>Looks like r is a very important parameter in our system, since its choice influencing the systems mechanics — larger <strong>r </strong>leads to more responsiveness.</p><p>Understanding and quantifying our system helps to design both the system and the controller/agent (by its cost function). The controller design has to ensure passengers’ comfort. Furthermore the system’s design tries to maximize the elevator’s dynamics (responsiveness) while minimizing energy consumption.</p><h3>Going nonlinear</h3><p>Our matrix based state space representation above applies only to a single operation point (e.g. x=10m) where the behavior is almost linear (with our simplified model). This is not always the case in general.</p><p>The general state-space equations for non-linear time-variant (vs. time invariant in the example above) systems are the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/0*QfYHEKsAbw1hoG8d.png" /></figure><p>The functions <strong>f</strong> and <strong>h </strong>can be nonlinear. How do we simulate such models? We cannot use the <strong>StateSpace</strong>class anymore. We need to switch to <strong>scipy.integrate.odeint </strong>in order to solve those differential equations.</p><p>For the sake of this example we will assume that the resistor <strong>R</strong> will increase its temperature with runtime <strong>t</strong> (see example plot below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/0*9_-I7jv936B-8DXq.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_UEv2hU4cgeBFNXqDVccw.png" /><figcaption>R_0 = 2Ω, T_R=3s</figcaption></figure><p>The following snippet is an example of calculating the step response (with height zero):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec599292bf591818641691828de5b891/href">https://medium.com/media/ec599292bf591818641691828de5b891/href</a></iframe><p>There are many more optional arguments for the <strong>odeint</strong> function (it uses FORTRAN library <strong>odepack</strong> in the background), feel free to read the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.odeint.html#scipy-integrate-odeint">official documentation</a>.</p><p>Let’s plot the result of the simulation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qd1TQFV51SeVsX9VriijoA.png" /></figure><h3>Conclusion</h3><p>In this article, I tried to show how to design and implement physical simulations in Python/SciPy for both linear and non-linear time-invariant systems. Designing such simulation frameworks helps to understand and quantify the environment where the future controller/agent will operate. Furthermore, it can help us to tweak the system itself (e.g. selecting certain mechanical components), presumably we have sufficient accurate mathematical description of system of interest.</p><p>A second motivation for this article was to demonstrate, that you don’t necessarily need MATLAB/Simulink for simple linear systems. If you have more complex behavior such as discrete and continuous elements / state machines and you want a nicer user interface to tweak and design your model, MATLAB/Simulink suite is the tool to go.</p><h3>Credits</h3><p>Thanks to Anna F. for reviewing this story.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=353eebf8dcc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/on-simulating-non-linear-dynamic-systems-with-python-or-how-to-gain-insights-without-using-ml-353eebf8dcc3">On simulating non-linear dynamic systems with Python or how to gain insights without using ML</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Understanding of Central Limit Theorem (visually)]]></title>
            <link>https://medium.com/analytics-vidhya/on-understanding-of-central-limit-theorem-visually-f70f9b0c02dc?source=rss-891434466d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f70f9b0c02dc</guid>
            <category><![CDATA[random-variable]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Marat Kopytjuk]]></dc:creator>
            <pubDate>Mon, 28 Oct 2019 17:13:18 GMT</pubDate>
            <atom:updated>2019-10-29T14:57:58.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eAMLGBSIDGq4zXUg" /><figcaption>Photo by <a href="https://unsplash.com/@ashenkris?utm_source=medium&amp;utm_medium=referral">Marcin Kempa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>During your statistics lectures you surely heard of the famous and fundamental <a href="https://en.wikipedia.org/wiki/Central_limit_theorem">Central Limit Theorem</a>. Especially for political surveys, drug effectiveness evaluations and A/B testing for digital goods this theorem allows us to draw conclusions from relatively small sample size in our tests. The “relatively small” refers to the whole population of objects/people/customers which are usually the goal of our investigation.</p><p>In this article I will introduce the most important concepts for applying Central Limit Theorem for inductive statistics and show with a simple visual example, how we get a normal distribution from the sum of any distributed random variable with a simple visual example.</p><p>You will probably need some basic statistics knowledge to follow the story-line, but I promise, you will get a new point of view about the fundamental thing many people in finance, engineering and medicine apply everyday!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2FMSClkmjZbhsvtl" /><figcaption>Monthly spending on clothes — Photo by <a href="https://unsplash.com/@beccamchaffie?utm_source=medium&amp;utm_medium=referral">Becca McHaffie</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How can we describe populations quantitatively? Let’s take an example. For monthly spending on clothes in central Europe a good descriptive metric would be the arithmetic mean (i.e. <em>average </em>or to be super precise: <em>expected value</em> <strong>µ</strong>). We have two options to find it out:</p><ol><li>Organize a survey of all adults in the region of interest (in our example whole Central Europe) and calculate the mean.</li><li>Take a sample, let’s say 1000 randomly selected adults, and calculate the average.</li></ol><p>It is obvious, that the first option would be the most precise but very expensive to organize, operate and evaluate. Just think of the amount of paperwork we would have to accomplish! Remember, not everyone has the ability to use computers and electronic forms and we want to include everyone in our survey to get a precise number!</p><p>The second option seems to be manageable, but surely not very precise, since taking a different “batch” of 1000 people(formally: sample size <strong>N=1000</strong>) over and over again will lead to different mean values. You could accidentally grab a group of fashion bloggers, or some tech-people, who spend their money on gadgets instead of different clothes (yes yes I know stereotypes everywhere …).</p><p>What happens statistically? By randomly selecting a single adult and asking for her/his monthly spending is equal to drawing from the random variable <strong>X, </strong>i.e. the measured spending <strong>x</strong> is a single <em>realization </em>of the random variable <strong>X</strong>.</p><p>Asking N adults and calculating the mean of their spending is the random variable <strong>S</strong>, defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*DxCtaGky7vYYWKytVny71g.png" /><figcaption>Random variable <strong>S</strong>: arithmetic mean of <strong>N</strong> equally distributed observations <strong>xi</strong></figcaption></figure><p>Let’s take a short look at the notation. We use capital letters (e.g. <strong>X</strong> and <strong>S</strong>) for random variables and small letters for their realizations (i.e. measurements).</p><p>Note, the sample distribution <strong>S</strong> is different to <strong>X</strong>. When you are reading the article always clarify whether <strong>S</strong> or <strong>X</strong> is mentioned.</p><p>Additionally not, that we do not know, how <strong>X</strong> is distributed. Is it a normal distribution? Poisson? Maybe <a href="https://en.wikipedia.org/wiki/F-distribution">F-distribution</a>? We do not know, but it doesn’t really matter!</p><p>Thanks to the Central Limit Theorem we know, that the sum of <strong>N</strong> equally distributed random variables <strong>X</strong> (no matter what kind of distribution) will lead to a normal distribution (for big sample sizes <strong>N</strong>).</p><p>What does it mean in our example? Taking a batch of adults and calculating arithmetical mean <strong>s </strong>is in other, more complicated words, drawing a realization from a normal distribution <strong>S</strong>. The shape and position of this normal distribution is important for us, since we will infer characteristics of <strong>X</strong> (average monthly spending per capita in Central Europe)<strong> </strong>out of it.</p><p>Namely, the central limit theorem states, that expected value of <strong>S </strong>equals to the expected value of <strong>X</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*wYLXgSNERBCNdJ08OrE9zg.png" /></figure><p>The variance of<strong> S </strong>equals the variance of<strong> X </strong>divided by the the sample size<strong> N</strong>, i.e.:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*gM7MxsieWsmdU0tw2FCs2Q.png" /></figure><p>This feels natural, since with increasing batch size, we get closer and closer to observing the whole population and the calculated mean won’t vary less and less between experiments.</p><p>Only in case you are interested in the theoretical background of the above formula, take a look at the <a href="https://en.wikipedia.org/wiki/Variance#Sum_of_uncorrelated_variables_(Bienaym%C3%A9_formula)">Bienaymé formula</a>.</p><h4>A closer look at CLT</h4><p>Now you surely ask <em>why </em>and <em>how </em>a sum of equal distributed random variables leads to a normal distribution without taking the shape of the distribution of <strong>X</strong> into account? This is actually the reason, why this article was written.</p><p>We find the answer deep in the statistics theory, namely in <a href="https://en.wikipedia.org/wiki/Convolution_of_probability_distributions">Convolution of probability distributions</a>. I described a simple sum of two random variables <a href="https://medium.com/analytics-vidhya/sum-of-two-random-variables-or-the-rocky-path-to-understanding-convolutions-of-probability-b0fc29aca3b5">in my last article</a>. There you’ll find a step by step example how the convolution operation is working and how it is calculated numerically.</p><p>Before dividing the sum of our measurements by <strong>N</strong>, we have a sum of <strong>N</strong> random variables <strong>S*</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*XlTpTC0l3w2jB9VJW-zCgw.png" /></figure><p>Imagine, the distribution of <strong>X</strong> would be a uniform distribution in the range of [0, 1]. We will increase the number of samples and see what effect it will take to the random variable <strong>S*</strong>.</p><p>The resulting random variable is the result of N convolutions (we convolve with the uniform distribution over our last result):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FU84pzAQRJfo%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DU84pzAQRJfo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FU84pzAQRJfo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2641e2e275c7bfcf78a1973e3729afa5/href">https://medium.com/media/2641e2e275c7bfcf78a1973e3729afa5/href</a></iframe><p>The convolution operation smooths out the shape of the uniform distribution. No matter what kind of distribution you will use, the result will be always the normal distribution!</p><p>Take a look at a very simple visual example from Wikipedia with an artificial distribution (read from top left to bottom right):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*iNZyhivILX0Zz37l.png" /><figcaption><a href="https://commons.wikimedia.org/wiki/File:Central_limit_thm.png">https://commons.wikimedia.org/wiki/File:Central_limit_thm.png</a></figcaption></figure><p>The more samples we take, the more the the sample mean’s distribution looks like normal distribution.</p><h4>Oh great, fancy plots, but how do they help me?</h4><p>Great question! Since we know, how our mean will be distributed, we can infer some useful information. After asking 1000 people about their outgoings, we can state, that the calculated mean value is within of certain bounds with 95% confidence, since we know about the variance of the resulting normal distribution of <strong>S</strong>.</p><p>Sounds complicated? Let’s talk about what confidence intervals are and how do we derive them.</p><h4>Confidence intervals</h4><p>The variance of <strong>S</strong> tells us sample mean’s magnitude of spread. In other words, small variance will lead to similar sample means and vice versa. Remember, the variance of <strong>S </strong>depends on the number of samples and the variance of <strong>X</strong> itself. Given a variance of <strong>X</strong> we can “adjust” the variance (standard deviation) of <strong>S</strong> by taking more or less measurements in our batch (i.e. we are varying <strong>N</strong>). The effect is stated in the equation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*yZIyGnqCE8aNXrGLSUvJsA.png" /><figcaption>Influence factors of <strong>σ²s</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*uvNd3whFs58SIEsJ.png" /><figcaption>Effect of different standard deviations on the shape of <strong>S </strong>— <a href="https://matheguru.com/stochastik/normalverteilung.html">https://matheguru.com/stochastik/normalverteilung.html</a></figcaption></figure><p>Back to our example, with a fixed sample size of <strong>N</strong> — how do we calculate confidence intervals? Let’s try to understand the concept step by step.</p><p>Imagine we would know the expected value <strong>µ</strong> in our experiment — theoretically we’ll expect <strong>µ</strong> to be in <strong>[µ-2*σ_s, µ+2*σ_s]</strong> in approx. 95% of all potentially possible experiments.</p><p>As a reminder an illustration of different σ intervals and their corresponding probabilities. There is a 34.1%+34.1%= 94.2% probability to draw a number in the interval of <strong>[-2σ, +2σ]</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81NAjPNeChdhqC5G.png" /><figcaption>Von M. W. Toews — Eigenes Werk, based (in concept) on figure by Jeremy Kemp, on 2005–02–09, CC BY 2.5, <a href="https://commons.wikimedia.org/w/index.php?curid=1903871">https://commons.wikimedia.org/w/index.php?curid=1903871</a></figcaption></figure><p>I know what you are thinking in the moment and you are right! We do not have any clue of <strong>µ</strong>. But having our sample mean <strong>s </strong>and <strong>[s-2*σ_s, s+2*σ_s] </strong>would give us an interval which will include <strong>µ</strong> with 95% confidence. Does it make sense? If not really, take a look at the picture below!</p><p>Firstly you’ll see the density curve, our sample mean’s distribution. Below, 25 different sample means with corresponding confidence intervals are illustrated (each of those is a single experiment with <strong>N</strong> participants). The interval length is the derived from the density curve‘s standard deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*Jqi4v7ctm_k-UTR-.png" /><figcaption><strong>X-bar</strong> equals to <strong>S</strong> in our example</figcaption></figure><p>Sure, as you see above, it is still possible to sample a mean somewhere far right (like the 5th sample) and the above mentioned <strong>[s-2σ_s, s+2σ_s] </strong>approach<strong> </strong>won’t include <strong>µ </strong>— but since sampling a mean far right to the true mean is highly unprobable, the approach seems to be valid — note, that there’s still a 5% chance to make a mistake (there’s still a reason why we gently say “with 95% confidence”).</p><p>In a nutshell: the interval boundaries indicate, that the true mean <strong>µ</strong> (i.e. the expected value we look for) will be within confidence boundaries in 95% (<strong>p</strong>=0.05) in all possible experiments we could potentially run. If we repeat the experiment infinite number of times and calculate the mean and confidence boundaries in the same manner as above, the expected value <strong>µ</strong> will be located within the confidence interval.</p><p>Anyway, it still can happen, that we observe some extremely high mean (because we had the bad luck to select a lot of fashion bloggers in our sample) and the confidence interval won’t include the true expected value. The chance of this event is <strong>p=0.05=5%</strong>. Surely, we theoretically could decrease <strong>p</strong> to 0 and require 100% confidence intervals (e.g. <strong>[s-10σ_s, s+10σ_s]</strong>), but this particular interval will be useless for us, since it will reach from <em>-inf</em> to <em>inf</em>.</p><p>In order to get smaller intervals and have the same magnitude of confidence the one and only way is to increase <strong>N</strong> to get a narrower sample distribution of <strong>S</strong>. Sorry :(</p><h3>Summary</h3><p>Whoa! That was a lot of content! What you definitely should understand, is the difference between the randomness of a single measurement <strong>X</strong> vs. the randomness of the sample mean <strong>S</strong>. Thanks to the central limit theorem and the convolution operation, the sum of <strong>N</strong> equally distributed random variables <strong>X</strong> will lead to a normal distribution without taking care of <strong>X</strong>’s probabilistic characteristics (we don’t even have to know the underlying distribution). The CLT allows us to do great things, such as estimating expected values and calculating intervals based on the confidence we specify beforehand.</p><p>Hope you had fun reading this article. I know, it is not an easy concept to grasp, but I am sure the article could provide a high level overview for a fundamental thing used across different domains in industry and academia.</p><h3>Credits</h3><p>Thanks to Anna F. for her support and the patience reading and correcting this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f70f9b0c02dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/on-understanding-of-central-limit-theorem-visually-f70f9b0c02dc">On Understanding of Central Limit Theorem (visually)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sum of 2 random variables: The rocky path to understanding convolutions of probability…]]></title>
            <link>https://medium.com/analytics-vidhya/sum-of-two-random-variables-or-the-rocky-path-to-understanding-convolutions-of-probability-b0fc29aca3b5?source=rss-891434466d3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0fc29aca3b5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[convolution]]></category>
            <category><![CDATA[control-theory]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Marat Kopytjuk]]></dc:creator>
            <pubDate>Thu, 03 Oct 2019 18:19:20 GMT</pubDate>
            <atom:updated>2019-10-17T04:43:15.922Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sum of two random variables or the rocky path to understanding convolutions of probability distributions</h3><p>During my master studies working through homework in probability theory I spend a bunch of hours of drinking coffee and struggling with an assignment, which seemed to be quite trivial at the first glance. Here it is:</p><blockquote>Given two independent uniformly distributed random variables <strong>X</strong> and <strong>Y</strong>, determine the probability density function<strong> p(Z=z)</strong> of <strong>Z=X+Y</strong> . Mathematically speaking:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*X7XbqHEW01zvKJQ5.png" /></figure><p>We can say, that the resulting function will have the range [0, 2] since there should be a probability for sampling both x=1 and y=1. <strong>But </strong>— just adding two uniform distributions won’t give us the right solution to the problem.</p><p>After a quick web search I found the theoretical tool, which is required to solve the task: <a href="https://en.wikipedia.org/wiki/Convolution_of_probability_distributions">Convolution of probability distributions</a>. It states:</p><blockquote>The general formula for the distribution of the sum <strong>Z=X+Y</strong> of two independent integer-valued (and hence discrete) random variables is</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*mpA2d_7afB_Up7Tn.png" /><figcaption>probability density of Z=X+Y given the (discrete) probability distributions of X and Y</figcaption></figure><blockquote>The counterpart for independent continuously distributed random variables with density functions <strong><em>𝑓,𝑔</em></strong> is</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*xnvnYarM1bjUYkPm.png" /><figcaption>probability density of Z=X+Y given the (continuous) probability densities of X and Y</figcaption></figure><p>My first thought was “oh, I saw those equation back in control theory lectures years ago (Laplace transformations)” — unfortunately years went by and I had no idea anymore how the integral</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*Z-z787kJ4bakBbBh.png" /></figure><p>is calculated. Sure, there are some fancy visualizations on pages wikipedia like the following one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*LWFWRQwofjc8slsg.gif" /></figure><p>but for me it was hard to decipher the meaning of the different variables within the equation. For example it was not clear to me, why the red function shifts to the left while the <strong>t</strong> argument is positive.</p><p>The goal of this blogpost is to dig through the convolution equation step by step — in the end you should feel comfortable working with convolutions and not be afraid of complex integrals.</p><p>Enjoy!</p><h3>Basics</h3><h4>Altering function graphs</h4><p>You probably had this chapter in school, teachers (at least in German schools) do that usually with quadratic functions. If you know what happens for function<strong> 𝑓</strong> after changing <strong>𝑓(𝑥) </strong>to <strong>𝑓(−𝑥+3) </strong>feel free to skip this section.</p><p>The motivation of this section is to understand the term <strong>𝑔(𝑧−𝑥)</strong> which is changed from <strong>𝑔(𝑥)</strong>.</p><blockquote>Note that I replaced the function argument <strong><em>𝑡</em></strong> with <strong><em>𝑥</em></strong> in order not to confuse the reader with <strong><em>𝑡</em></strong> as “time”. We will continue to use <strong>x</strong> throughout this blog article.</blockquote><p>Let’s define two simple functions to work through this tutorial. The first will be a simple quadratic function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/0*atmj6rfL99k5qHzv.png" /></figure><p>As I want to accomplish my homework assignment, too — we will have a uniform distribution <strong>U([0, 1])</strong> as our second function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/0*R5AiWGo8lsylNrgH.png" /></figure><p>Let’s visualize both in one picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTHHVeOT5A0hNSysigtnJQ.png" /></figure><p>Now what happens when we add a constant <strong>𝑧</strong> to the function argument (i.e. <strong>𝑓(𝑥+3)</strong>)? Let’s see what happens for different values of <strong>𝑧</strong>. We will do a single plot for each example function, here for the quadratic:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkWsCGXeQkr8AkqqYzsPEA.png" /></figure><p>Adding a positive number <strong>z</strong>, we shift the graph to the left, with a negative <strong>z</strong> to the right.</p><p>What happens if we multiply <strong>−1</strong> to the function argument <strong>x</strong>? We show this effect on the uniform function, since the quadratic graph is symmetric and will show no change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rZPc6t81LWqUmu7BKr4noQ.png" /></figure><p>Apparently, adding a negative sign to <strong>x</strong> “mirrors” the function graph relative to the y-axis.</p><p>Now we can understand the transformation <strong>g(x)</strong> to <strong>g(z−x)</strong>. It simply describes adding a constant <strong>z</strong> (shifting it to the left) and multiplying <strong>−1</strong> to <strong>x </strong>(mirroring it relative to the y-axis)<strong>.</strong></p><p>See the effect on the dotted function graphs below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phW0w2DBj0giMQ35olouPQ.png" /></figure><h4>Multiplying two functions</h4><p>Let’s continue to work through the convolution calculation formula — our next task is to understand the product of two functions (or in my case density distributions):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/0*FDf8R19a37ugxywg.png" /></figure><p>What happens if we multiply them?</p><p>Let’s define a proxy function <strong>a(x)</strong> as a product of both example functions and visualize all three:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/0*3bE--nOOE9RBS6nW.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jq4zVmmrVcx7EpAvLdS1GQ.png" /></figure><p>The black dotted graph is the product function we integrate on in the next step. Since both rectangle functions do not overlap completely, the resulting graph is not as wide as both source functions.</p><h4>Integrating over the product function a(x)</h4><p>An integral is the area between the function graph and the x-axis. This is the last building block of our convolution procedure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*-gKvT_b3GploMdsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWKK_mXThZ_tsKAuVCYP_g.png" /></figure><p>The integral over the product of two uniform probability densities <strong>f</strong> and <strong>g</strong> (one of them shifted to the right by 0.5) is <strong>0.5</strong>.</p><p>Wow that was a lot… Let’s summarize everything in one picture!</p><h3>Collecting the building blocks</h3><p>Finally we are ready to understand the convolution equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*0Kpz67WICAQg7Oqs.png" /></figure><p>In order to calculate <strong>h(z)</strong> for a particular <strong>z</strong> we have to do following steps:</p><ol><li>Shift function <strong>g(x)</strong> to the left <strong>z</strong>, i.e.<strong> g(x+z)</strong></li><li>Mirror the result relative to the y-axis, i.e. <strong>g(−x+z)=g(z−x)</strong></li><li>Calculate the product <strong>a(x),</strong> i. e.<strong> f(x)g(z−x)=a(x)</strong></li><li>Calculate the infinite integral over <strong>a(x)=i</strong></li><li>The result of the convolution at particular position <strong>z</strong> is <strong>i</strong>, i.e. we calculated <strong>h(z)=∫ f(x)g(z−x)dx</strong>.</li></ol><p>We apply this procedure for each <strong>z </strong>we are interested in, usually it is a range, for calculating a particular probability.</p><p>Now having the procedure to calculate convolutions, we can apply it to the initial question (my study assignment):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*pslHpbv8dgX06m_z.png" /></figure><p>We calculate and visualize the result for <strong>z</strong> in range from -1 to 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wknPJBwyoom_PeBtM74cSQ.png" /></figure><p>Nice! As expected, the final probability distribution is not a uniform distribution. We see that the sum of two equally distributed random variables will lead to a “triangular” probability density!</p><p>Its shape also looks plausible and intuitive, since the expected values of <strong>X</strong> and <strong>Y</strong> are both 0.5 (remember, both were uniformly distributed in [0,1]) the expected value for Z has to be 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*YVbXUvh5gtijo2asY5rFBg.png" /></figure><p>Thank you for your attention and drop your comments below!</p><p>For creating the plots I used Python and <em>matplotlib </em>package. Calculation for integrals was done with <em>scipy.integrate.trapz</em> function.</p><p>Special thanks to <a href="https://github.com/herzog-ch">https://github.com/herzog-ch</a> for his review!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0fc29aca3b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/sum-of-two-random-variables-or-the-rocky-path-to-understanding-convolutions-of-probability-b0fc29aca3b5">Sum of 2 random variables: The rocky path to understanding convolutions of probability…</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>