Euler's Method with Python
Total Page:16
File Type:pdf, Size:1020Kb
Johanna M Debrecht Page | 1 Euler’s Method with Python Differential Equations Lab Description In this lab, we are going to explore Euler’s method of solving first-order, initial value problem differential equations by writing a program in Python. You do not need to be an expert at Python, or even know the language yet to complete the lab. You also do not need to have python installed on your computer, but you will need access to the internet. All the code you need is contained in this document. Remember, Euler’s method uses tangent lines and the Linear Approximation function from calculus to approximate solutions to differential equations. The primary value of studying Euler’s method is pedagogical, as it is a good introduction to the ideas used in numerical integration of differential equations (DEs). However, it has limited use because of the error that increases with each step. Euler’s Method Overview and Review Given a first-order, initial value problem of the form: y′ = f( xy,) , yx( 00) = y, we will build a basic program to approximate the solution using Euler’s method. To begin, we need to decide over what interval xx0 , p we wish to find a solution. We will also need to decide how many points n within the interval that we wish to approximate. Thus, the lengths of our “steps” h will be given by xx− h = p 0 . n −1 Johanna M Debrecht Page | 2 This will generate n evenly spaced points xx01, ,... xp , where xk = x0 +⋅ kh. Our goal is to produce a table like the following, with the program filling in the yx( k ) values (similar to Table 2.6.1 or Table 2.6.2 on p. 78 of the textbook). xy xy00 x11 yx( ) x22 yx( ) xpp yx( ) Recall that the accuracy of Euler’s method improves if you make the “step” size h smaller; that is, if you take more points on the interval (increase n). The width of the interval will also affect the accuracy of the approximation. Larger intervals will be less accurate, so you would want to use more points on the interval. We know that yx( 00) = y, which means that yx′( 0) = fxy( 00,.) Using the linear approximation function, (which is a tangent line approximation to the function), we can write yx( ) ≈ yx( 0) + y′( x 000000)( x −=+ x) y f( x, y)( x − x), for all x close to x0 . Hence, we can approximate that yx( 1) ≈= y 1 Lx( 1) = yx( 0) + f( x 00, y)( x 1 − x 0) =+ y 0 hfx( 00, y). Then, since yx( 11) ≈ y, we can substitute into the DE to get yx′( 1) = fx( 1, yx( 1)) ≈ fx( 11, y). Therefore, the linear (tangent line) approximation function becomes yx( ) ≈ yx( 1) + y′( x 111111)( x − x) ≈+ y f( x, y)( x − x), for all x close to x1. Using the same process, we approximate that yx( 2) ≈ yx( 1) + fxyx( 11, )( 2 −≈=+ x 1) y 2 y 1 fxyx( 11, )( 2 −=+ x 1) yhfxy 1( 11, ). Johanna M Debrecht Page | 3 In this fashion, we can find approximations for yx( kk) ≈ y, where the yk are defined recursively by the formula yk+1 = y k + hf( x kk, y ). The table of values produced in this way generates a list of points that approximate the solution to the DE. This is Euler’s method. Coding Euler’s Method Using Python: Part 1 Step 1 SageMath is a free open-source mathematics software system licensed under the GPL (General Public License). Through it, you can get free access to python, R (used in statistics), Octave, java, C++, fortran, SageMath, Julia, and others. Go to the following website and create an account https://cocalc.com (Collaborative Calculation in the Cloud). Step 2 Click on the orange ball surrounded by the blue arcs on the upper left of your home page. Click on “Create a New Project,” give it a title, then click on “Create Project.” When created, click on the title to open it. Johanna M Debrecht Page | 4 Step 3 At the top, in the banner, you will see the following. Click on “New.” Click on “Sage worksheet” in the first row, upper left. You should now see something like the following. Step 4 We will be writing our code in the big empty space, starting where you see the horizontal blue line. We need to load some software packages, written by others, to assist us in our calculations Johanna M Debrecht Page | 5 and graphing. For example, numpy is a library containing a vast number of routines for numerical calculation in python, and matplotlib contains packages for plotting and graphing. You will also need to put your name into the file. You can do that by enclosing it between triple quotation marks. Anything between triple quotation marks will be ignored by Python. (See Substep G for a note about quote marks.) For a single line comment, you can put a hashtag or # at the beginning of that one line. Substep A Type in the following code: Import Packages from External Libraries """Put Your Name Here""" import numpy as np from matplotlib import pyplot as plt You should be able to copy/paste it in. Substep B Now we need to enter some information about our initial value, the width of the interval, the number of data points we want approximated, and the size of our steps h. For the purposes of this lab, I am going to use the following DE as an example y′ =+=0.1 y 0.4 xy2 , (2) 4. Suppose we would like to approximate over the interval [2, 2.5] with n = 101. Then x00=2, y =4, xpp =2.5, n =101, and hxx =( −0) ( n −=1) 0.005. Type in the following code to enter this information. Johanna M Debrecht Page | 6 Define Your Basic Values x0=2 y0=4 xp=2.5 n=101 step_h=(xp-x0)/(n-1) Substep C In order to enter our x-values, we need to create a 101-tuple, or vector. The entries will be our x- values, [2.0, 2.005, 2.01, 2.015, , 2.5] . Enter the following code to define this vector. Create a Vector of the x-Values x=np.linspace(x0,xp,n) Substep D Now that we have coded our x-values, we need to code how to generate the y-values. We will have to create a place to store the y-values. We will use an array (an ordered list with only one row or only one column) with n entries all set to 0.0. Enter the following code to create an array for storing the y-values. Create an Array for the y-Values y=np.zeros([n]) Substep E We are now ready to code the part that uses Euler’s method. We need to replace the entries in the y array (initially set to 0) with the approximations generated by Euler’s method. Since this is an iterative process, we will use what is called a for loop in programming. This will cause the computer to repeat the steps inside the for loop a specified number of times. The first line in the following box resets the first entry in the y array to the value of y0 = 4. (Remember that we set this in the code already with y0=4 in Substep B.) Johanna M Debrecht Page | 7 The second line sets up a “dummy” variable to iterate for our for loop. Because the next line is indented (you must use a tab), then the variable will only be available for this level or one below it. When we move out of the tabbed area, it won’t apply any more. The tab is critical; this is how python knows what belongs to what. Everything that is indented after the for will be considered part of the loop until the first line that is not indented. The next line sets the kth entry of our y array to be the value of the (k − 1)th entry of the y array added to h times the approximated value of the DE’s derivative. This line will input the approximated values of the solution to the DE into the y array, using Euler’s method. Create a for loop y[0]=y0 for k in range(1,n): y[k]=y[k-1]+step_h*(0.1*(np.sqrt(y[k-1]))+0.4*(np.power(x[k-1],2))) Substep F Since we have gone to all this trouble, we should definitely print out our results! We will use another for loop to print out our approximated values for the solution. Print the Approximated Solution Values for k in range(n): print(x[k],y[k]) Substep G Finally, we want to make a graph of our result. We can use the plot function from matplotlib to do this (in the second line we called it in as plt). Caution! Depending on the font you are using, python may not like your single and/or double quote marks. If you see the error in red (below the code in Plot the Solution), that is what happened. You can type them directly into the worksheet. (You may not have noticed, but if they were incorrect, they would have shown up as red in the code.) Johanna M Debrecht Page | 8 Plot the Solution plt.plot(x,y,’o’) plt.xlabel(“Value of x”) plt.ylabel(“Value of y”) plt.title(“Approximate Solution with Euler’s Method”) plt.show() Let me guess—you fixed all the single and double quotes, but you still have an error.