User-Defined Function
|
|
- Rosalyn Newman
- 5 years ago
- Views:
Transcription
1 ENGR (Socolofsky) Week 11 Python scripts In the lecture this week, we are continuing to learn powerful things that can be done with userdefined functions. In several of the examples, we consider a quadratic equation in the form f(x) = ax 2 + bx + c (1) and these examples could be done in nearly the same way with any other function f(x). The set of scripts below contain a module of functions and a set of examples/tests contained within an if name is main : block. One thing you will notice in this script is that we import modules as needed throughout the code. This is useful to avoid importing large packages into memory before they are needed. This also isolates these complex packages from the rest of the code, where they are not needed. Whether all packages are imported at the top of the code or as needed is a matter of taste, and the examples below follows the approach of keeping numerical packages together with the code that performs the numerical analysis. A User-Defined Function The function quadratic eqn() is a user-defined function to compute the quadratic equation at a point x given the coefficients a, b, and c. This function can take x as an integer, real number, np.array object, or a complex number and returns the corresponding value of f(x). If we want to use a root-finding method to find the roots of the quadratic equation when the roots are complex, we need to adapt the quadratic eqn() function to return the real and imaginary parts of x and f(x) as separate, real, floating-point numbers. There are different ways to do this, and in the script below, we choose to return these as real numbers in a 2 1 np.array. For example, if the x-coordinate is i, then we would store this as x = np.array([7.2, -8.6]) The function quadratic complex() in the script below takes x in this format as input, converts it to a complex number using the built-in Python function complex(), passes this x value to quadratic eqn() to compute the value of f(x), and returns the possibly complex result as a 2 1 np.array object. B Passing Functions to Functions A key concept needed to make functions that solve mathematical problems more general is the ability to pass a user-defined function that contains the particular problem of interest to the function that performs the numerical solution. We demonstrate passing a function to a function using the function plot fun(), defined in the script below. This function takes a user-defined function in the form func(x, params) as input together with the lower and upper bounds on the x-axis for
2 plotting, an optional input that contains the params for func, and an optional figure number as input. We use tuples to pass multiple parameters through the variable params to the user-defined function func. Here, we demonstrate using quadratic eqn() as the function for func. plot fun() then computes an array of x and f(x) data and plots the data over the desired range in the given figure number. C Examples In the script below, we use scipy to solve several, typical mathematical problems in science and engineering. C.1 Integration As an example of integration, we use scipy.integrate.quad() to evaluate the integral b f(x)dx a using the quadratic equation in quadratic eqn() as an example for f(x). The function quadratic eq int() returns the analytical solution for the integral of a quadratic equation, and the script tests below compare the result returned by quad() to this analytical solution. C.2 Root-Finding There are multiple methods to find roots available within scipy, and here we demonstrate the function scipy.optimize.fsolve() for the problem f(x) = 0 (3) where we use the quadratic equation as an example of f(x). In the example in the script, we look for complex roots; hence, we use the function quadratic complex() with fsolve(). The function quadratic roots() computes the roots using the quadratic formula, and this analytical solution is compared with the roots returned by fsolve(). (2) C.3 Interpolation As an example of interpolation, we use some sparse data for the temperature and salinity as a function of depth in the ocean. There are interpolation methods in scipy and numpy, and we demonstrate scipy.interpolate.interp1d(). The data and the example are all contained within the examples at the bottom of the script, and this example does not use any of the user-defined function defined in the main body of the script module. C.4 Ordinary Differential Equations There are two main solver function for ordinary differential equations (ODEs) in scipy, and here we demonstrate scipy.integrate.odeint(). The general form of a one-dimensional ODE is dy dt = f(y, t) (4) 2
3 subject to the initial condition y(0) = y 0. In the example below, we consider f(y, t) = ky. To solve ODEs numerically, we need to write a function that returns f(y, t); in the sample script this is diff eq rhs(). We compare the results of odeint() to the analytical solution, given by y(t) = y 0 exp( kt) (5) The sample script that performs all of these examples and contains each of the required userdefined functions is given below in the script fun script.py 3
4 Listing for the script fun script.py 1 # fun_script.py 2 # 3 # This program demonstrates passing functions to functions and using SciPy 4 # 5 # S. Socolofsky 6 # ENGR # October import numpy as np # Fuction definitions def quadratic_eqn (x, a, b, c): 14 """ 15 Function to compute the quadratic equation Computes the quadratic equation, defined by: 18 f( x) = ax ^2 + bx + c 19 at a given value of x for given coefficients a, b, and c Parameters x : float or np. array 24 Value ( s) of the independent variable 25 a, b, c : float 26 Coefficients of the quadratic equation Returns f( x) : float or np. array 31 Value ( s) of the corresponding dependent variable """ 34 return a * x** 2 + b * x + c def quadratic_ complex (x, a, b, c): 37 """ 38 Compute complex values for the quadratic equation Compute the quadratic equation for values of x for which x and / or f( x) is 41 complex Parameters x : np. array 46 Value of the independent variable stored in an array containing the 47 real and imaginary parts separately, e. g., np. array ([ x. real, x. imag ]) 48 a, b, c : float 49 Coefficients of the quadratic equation 4
5 50 51 Returns x : np. array 54 Array containing the real and imaginary parts of f( x) Notes Uses the function quadratic_ eqn (x, a, b, c) to compute the quadratic 59 equation """ 62 fc = quadratic_eqn ( complex (x[0], x[1]), a, b, c) 63 return np. array ([ fc.real, fc. imag ]) def quadratic_eqn_int ( lim_a, lim_b, a, b, c): 67 """ 68 Function to compute the integral of the quadratic equation Computes the integral of the quadratic equation given by: 71 f( x) = ax ^2 + bx + c 72 with the limits of integration spanning ( lim_a, lim_b ) Parameters lim_a : float 77 Lower bound for the limits of integration 78 lim_b : float 79 Upper bound for the limits of integration 80 a, b, c : float 81 Coefficients of the quadratic equation Returns g( x) : float 86 The value of the definite integral of the quadratic equation with the 87 given limits of integration """ 90 fun = lambda x: a * x** 3 / 3. + b * x** 2 / 2. + c * x return fun ( lim_b ) - fun ( lim_a ) def quadratic_ roots (a, b, c): 96 """ 97 Compute the roots of the quadratic equation Computes the roots of the quadratic equation, defined by: 100 f( x) = ax ^2 + bx + c 101 using the analytical solution 102 xr = (-b +/ - sqrt (b^2-4ac )) / (2a) 5
6 103 where the solution is returned as a float ( complex as needed ) Parameters a, b, c : float 108 Coefficients of the quadratic equation Returns xr : np. array 113 Array containing the two roots of the quadratic equation, each as 114 an array containing the real and imaginary parts of the root """ 117 # Compute the discriminant 118 d = b**2-4. * a * c # Find the roots assuming a is not zero 121 if d >= 0.: 122 x0 = (-b - np. sqrt (d)) / (2 * a) 123 x1 = (-b + np. sqrt (d)) / (2 * a) 124 else : 125 x0 = complex (-b / (2 * a), -np. sqrt (-d) / (2 * a)) 126 x1 = complex (-b / (2 * a), np. sqrt (-d) / (2 * a)) # Return the roots as np. arrays 129 return (np. array ([x0.real, x0. imag ]), np. array ([x1.real, x1. imag ])) def diff_eq_rhs (y, t, k): 133 """ 134 Function containing the RHS of a differential equation Function to solve the ODE given by 137 dy/dt = -ky 138 using the scipy. integrate. odeint () function. This function contains 139 the right - hand - side ( RHS ) of this ODE Parameters y : np. array 144 Array of dependent variable value ( s) 145 t : float 146 Value of the independent variable 147 k : float 148 Die - off rate constant for the growth model dy/ dx = - ky in dimensions 149 of 1 / t Returns dy/dt : np. array 154 Array of value ( s) returning the RHS of the ODE to solve. This is the 155 local slope of the solution y( t). 6
7 """ 158 return - k * y def plot_fun (fun, x0, xf, params =(), fnum =1): 162 """ 163 Plot a function f( x) over the range ( x0, xf) Plot a function f( x) given by the name fun over the range of independent 166 variables between x0 and xf Parameters fun : function 171 Name of a Python function to compute the dependent variable. Should 172 be in the form fun (x, params ), where x can accept a np. array input 173 and the additional params are optional. 174 x0 : float 175 Minimum independent variable value in range to plot 176 xf : float 177 Maximum independent variable value in range to plot 178 params : tuple, default () 179 Optional parameters to pass to the function fun 180 fnum : int 181 Figure number to plot """ 184 # Create an array of independent variables 185 xp = np. linspace (x0, xf, num =250) # Compute the corresponding dependent variables 188 yp = fun (xp, * params ) # Create the desired plot 191 import matplotlib. pyplot as plt 192 plt. figure ( fnum ) 193 plt. gcf (). clear () 194 plt. plot (xp, yp, 'b-') 195 plt. xlabel ('x') 196 plt. ylabel ('f(x)') 197 plt. grid ( True ) 198 plt. show () # Testing procedures if name is ' main ': """ 206 Test procedures that execute if this script is run from the command prompt Examples using user - defined functions to perform typical simulation 7
8 209 exercises, including integration, root finding, interpolation, and 210 solving ordinary differential equations The examples below include the following : ) Compute the quadratic equation using a user - defined function ) Plot a user - defined function by passing a function and optional 216 arguments to another function that plots the results ) Integrate a quadratic equation over fixed limits of integration 218 a.) using scipy. integrate. quad () 219 b.) using the analytical solution ) Find the roots of the quadratic equation ( including imaginary 221 roots ): 222 a.) using scipy. optimize. fsolve () 223 b.) using the quadratic formula ) Interpolate multidimensional data using 225 a.) scipy. interpolate. interp 1d() for linear interpolation 226 b.) scipy. interpolate. interp 1d() for cubic interpolation ) Solve the differential equation dy/ dt = - ky; y( 0) = y0 228 a.) using scipy. integrate. odeint () 229 b.) using the analytical solution """ # Examples using the quadratic equation x = a, b, c = 1.0, 1.5, print (' Testing the quadratic equation function for the equation :') 238 print (' f(x) = ' + str (a) + 'x^2 + ' + str (b) + 'x + ' + str (c)) # Compute a single point 241 print ('\ nthe solution at x =', x, 'is:') 242 print (' ' + str ( quadratic_eqn (x, a, b, c ))) # Compute using a np. array of 5 points 245 x = np. linspace (-3., 3., num =5) 246 print ('\ nthe solution at x =', x, 'is:') 247 print (' ' + str ( quadratic_eqn (x, a, b, c ))) # Plot this quadratic equation over the range (- 3, 3) 250 fnum = print ('\ nplotting the quadratic equation over the range ') 252 print (' (' + str (x. min ()) + ', ' + str (x. max ()) + ') in Figure ' str ( fnum )) 254 plot_fun ( quadratic_eqn, -3, 3, (a, b, c), fnum ) # Example integrating a quadratic equation over the range (- 3, 3) from scipy. integrate import quad 258 lower_ limit = upper_ limit = scipy_ integral = quad ( quadratic_eqn, lower_limit, upper_limit, 261 args =(a, b, c ))[ 0] 8
9 262 print ('\ nscipy returns the integral of this quadratic equation with ') 263 print (' limits of integration spanning (' + str ( lower_ limit ) + ', ' str ( upper_limit ) + ') as:') 265 print (' ' + str ( scipy_ integral )) # Compare to the true value of the integral 268 true_ integral = quadratic_ eqn_ int ( lower_limit, upper_limit, *( a, b, c)) 269 print ('\ nthe true value of this integral is:') 270 print (' ' + str ( true_ integral )) # Example finding roots of a quadratic equation from scipy. optimize import fsolve 274 x0 = np. array ([ -1., -1.]) 275 sol = fsolve ( quadratic_ complex, x0, args =( a, b, c)) 276 print ('\ nscipy returns the roots of this quadratic equation near ') 277 print (' x0 = ' + str (x0[0]) + ' + (' + str (x0[1]) + ')i as:') 278 print (' ' + str ( sol [0]) + ' + (' + str ( sol [1]) + ')i') 279 x0 = np. array ([ -1., 1.]) 280 sol = fsolve ( quadratic_ complex, x0, args =( a, b, c)) 281 print (' And Scipy returns the roots of this quadratic equation near ') 282 print (' x0 = ' + str (x0[0]) + ' + (' + str (x0[1]) + ')i as:') 283 print (' ' + str ( sol [0]) + ' + (' + str ( sol [1]) + ')i') # Compare to the analytical solution for the roots of a quadratic equation 286 sol = quadratic_ roots (a, b, c) 287 print ('\ nthe true values for these roots are :') 288 print (' ' + str ( sol [0][0]) + ' + (' + str ( sol [0][1]) + ')i') 289 print (' ' + str ( sol [1][0]) + ' + (' + str ( sol [1][1]) + ')i') # Example using interpolation z = np. array ([0., 10., 50., 100., 200., 1000.]) 293 T = np. array ([23.4, 18.7, 17.9, 16.7, 10.5, 9.9]) 294 S = np. array ([32.5, 33.5, 33.7, 33.8, 34.5, 34.51]) 295 print ('\ nconsider the temperature ( deg C) and salinity ( psu ) data ') 296 print (' versus depth ( m) given by:') 297 print (' z :', z) 298 print (' T :', T) 299 print (' S :', S) # Create an interpolation function that has z as independent variable and 302 # T and S as dependent variables. 303 from scipy. interpolate import interp 1d 304 data = np. vstack ((T, S)) 305 interp_ linear = interp 1d(z, data ) 306 interp_ cubic = interp 1d(z, data, kind =' cubic ') # Compute points using interpolation 309 print ('\ nthe temperature and salinity at z = 75 m is:') 310 print (' Linear interpolation :', interp_ linear ( 75.)) 311 print (' Cubic interpolation : ', interp_ cubic ( 75.)) # Plot the profiles 314 zp = np. linspace (z. min (), z. max (), num =250) 9
10 315 yp_lin = interp_ linear ( zp) 316 yp_cub = interp_ cubic ( zp) 317 import matplotlib. pyplot as plt 318 fnum = print ('\ nplotting this temperature profile using linear and cubic ') 320 print (' interpolation in Figure ' + str ( fnum )) 321 plt. figure ( fnum ) 322 plt. gcf (). clear () 323 plt. plot (T, z, 'o') 324 plt. plot ( yp_lin [0,:], zp, 'b-') 325 plt. plot ( yp_cub [0,:], zp, 'g-') 326 plt. xlabel ('Temperature ( deg C)') 327 plt. ylabel ('Depth (m)') 328 plt. gca (). invert_yaxis () 329 plt. grid ( True ) 330 plt. legend (( ' Data ', ' Linear Interpolation ', ' Cubic Interpolation ')) 331 plt. show () # Example solving an ordinary differential equation ( ODE ) t = np. linspace (0., 10., num =5) 335 y0 = k = # Use scipy to solve the ODE dy/ dt = - ky subject to the initial condition 339 # y( 0) = from scipy. integrate import odeint 341 sol = odeint ( diff_eq_rhs, y0, t, args =( k,)) 342 print ('\ nthe Scipy solution to the differential equation :') 343 print (' dy/dt = -ky ') 344 print (' with initial condition y( 0) = ', y0, ' is:') 345 print (' t:', t) 346 print (' y:', sol [:,0]) # The analytical solution is y = y0 exp (- kt )... report this 349 print ('\ nthe analytical solution for this case is:') 350 print (' t:', t) 351 print (' y:', y0 * np.exp (-k * t)) 10
11 Code execution for fun script.py yields Testing the quadratic equation function for the equation: f(x) = 1.0x^ x The solution at x = 2.0 is: 9.0 The solution at x = [ ] is: [ ] Plotting the quadratic equation over the range (-3.0, 3.0) in Figure 1 Scipy returns the integral of this quadratic equation with limits of integration spanning (-3.0, 3.0) as: 30.0 The true value of this integral is: 30.0 Scipy returns the roots of this quadratic equation near x0 = (-1.0)i as: ( )i And Scipy returns the roots of this quadratic equation near x0 = (1.0)i as: ( )i The true values for these roots are: ( )i ( )i Consider the temperature (deg C) and salinity (psu) data versus depth (m) given by: z : [ ] T : [ ] S : [ ] The temperature and salinity at z = 75 m is: Linear interpolation: [ ] Cubic interpolation: [ ] 11
12 Plotting this temperature profile using linear and cubic interpolation in Figure 2 The Scipy solution to the differential equation: dy/dt = -ky with initial condition y(0) = 1.0 is: t: [ ] y: [ ] The analytical solution for this case is: t: [ ] y: [ ] 12
13 The two figures produced by this script are shown in Figures 1 and f(x) x Figure 1. Plot of the quadratic equation over the range ( 3, 3) using quadratic eqn() and plot fun() in the script fun script.py. 13
14 0 200 Data Linear Interpolation Cubic Interpolation Depth (m) Temperature (deg C) Figure 2. Plot of data for temperature as a function of depth in the ocean using the raw data, linear interpolation, and cubic interpolation based on scipy.interpolate.interp1d() as demonstrated in fun script.py. 14
ENGR (Socolofsky) Week 07 Python scripts
ENGR 102-213 (Socolofsky) Week 07 Python scripts A couple programming examples for this week are embedded in the lecture notes for Week 7. We repeat these here as brief examples of typical array-like operations
More informationPython Crash Course Numpy, Scipy, Matplotlib
Python Crash Course Numpy, Scipy, Matplotlib That is what learning is. You suddenly understand something you ve understood all your life, but in a new way. Doris Lessing Steffen Brinkmann Max-Planck-Institut
More informationENGR (Socolofsky) Week 02 Python scripts
ENGR 102-213 (Socolofsky) Week 02 Python scripts Listing for script.py 1 # data_types.py 2 # 3 # Lecture examples of using various Python data types and string formatting 4 # 5 # ENGR 102-213 6 # Scott
More informationPart VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,
Part VI Scientific Computing in Python Compact Course @ Max-PlanckMarch 6-10, 2017 63 Doing maths in Python Standard sequence types (list, tuple,... ) Can be used as arrays Can contain different types
More informationMS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing
MS6021 Scientific Computing TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing Preliminary Notes on Python (v MatLab + other languages) When you enter Spyder (available on installing Anaconda),
More informationNumerical Calculations
Fundamentals of Programming (Python) Numerical Calculations Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Scipy Lecture Notes at http://www.scipy-lectures.org/ Outline
More informationLecture 8: Euler s Methods
Lecture 8: Euler s Methods Forward Euler Method The formula for the forward Euler method is given by equation (8.2) in the lecture note for week 8, as y i+1 = y i + f(x i, y i )h. (1) where f(x i, y i
More informationNumerical Integration
Numerical Integration 1 Functions using Functions functions as arguments of other functions the one-line if-else statement functions returning multiple values 2 Constructing Integration Rules with sympy
More informationIntroduction to Scientific Computing with Python, part two.
Introduction to Scientific Computing with Python, part two. M. Emmett Department of Mathematics University of North Carolina at Chapel Hill June 20 2012 The Zen of Python zen of python... fire up python
More informationBi 1x Spring 2014: Plotting and linear regression
Bi 1x Spring 2014: Plotting and linear regression In this tutorial, we will learn some basics of how to plot experimental data. We will also learn how to perform linear regressions to get parameter estimates.
More informationChapter 2. MathScript
Chapter 2. MathScript 2.1 What is MathScript MathScript is math-oriented, text-based computing language to address tasks mathematic calculation: Most suitable for Mathematic calculation. Matrix based data
More informationUNIT 3 EXPRESSIONS AND EQUATIONS Lesson 3: Creating Quadratic Equations in Two or More Variables
Guided Practice Example 1 Find the y-intercept and vertex of the function f(x) = 2x 2 + x + 3. Determine whether the vertex is a minimum or maximum point on the graph. 1. Determine the y-intercept. The
More informationObject Oriented Programming Using C++ Mathematics & Computing IET, Katunayake
Assigning Values // Example 2.3(Mathematical operations in C++) float a; cout > a; cout
More informationPart VI. Scientific Computing in Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,
Part VI Scientific Computing in Python Compact Course @ Max-Planck, February 16-26, 2015 81 More on Maths Module math Constants pi and e Functions that operate on int and float All return values float
More informationInterpolation and curve fitting
CITS2401 Computer Analysis and Visualization School of Computer Science and Software Engineering Lecture 9 Interpolation and curve fitting 1 Summary Interpolation Curve fitting Linear regression (for single
More informationChapter 8 Complex Numbers & 3-D Plots
EGR115 Introduction to Computing for Engineers Complex Numbers & 3-D Plots from: S.J. Chapman, MATLAB Programming for Engineers, 5 th Ed. 2016 Cengage Learning Topics Introduction: Complex Numbers & 3-D
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;
More informationTutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )
Tutorial 2 PHY409 Anadi Canepa canepa@triumf.ca Office, TRIUMF MOB 92 B (1-604- 222-7330) Alan Manning mannin2@phas.ubc.ca Mohammad Samani samani@physics.ubc.ca During the 1 st tutorial We learnt What
More informationUNIT 8: SOLVING AND GRAPHING QUADRATICS. 8-1 Factoring to Solve Quadratic Equations. Solve each equation:
UNIT 8: SOLVING AND GRAPHING QUADRATICS 8-1 Factoring to Solve Quadratic Equations Zero Product Property For all numbers a & b Solve each equation: If: ab 0, 1. (x + 3)(x 5) = 0 Then one of these is true:
More informationIntegration. Volume Estimation
Monte Carlo Integration Lab Objective: Many important integrals cannot be evaluated symbolically because the integrand has no antiderivative. Traditional numerical integration techniques like Newton-Cotes
More informationUNIVERSITETET I OSLO
(Continued on page 2.) UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Examination in: INF1100 Introduction to programming with scientific applications Day of examination: Thursday, October
More informationEffective Programming Practices for Economists. 10. Some scientific tools for Python
Effective Programming Practices for Economists 10. Some scientific tools for Python Hans-Martin von Gaudecker Department of Economics, Universität Bonn A NumPy primer The main NumPy object is the homogeneous
More informationWK # Given: f(x) = ax2 + bx + c
Alg2H Chapter 5 Review 1. Given: f(x) = ax2 + bx + c Date or y = ax2 + bx + c Related Formulas: y-intercept: ( 0, ) Equation of Axis of Symmetry: x = Vertex: (x,y) = (, ) Discriminant = x-intercepts: When
More informationAlgebra 1 Semester 2 Final Review
Team Awesome 011 Name: Date: Period: Algebra 1 Semester Final Review 1. Given y mx b what does m represent? What does b represent?. What axis is generally used for x?. What axis is generally used for y?
More informationLECTURE 19. Numerical and Scientific Packages
LECTURE 19 Numerical and Scientific Packages NUMERICAL AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that
More informationSymbols. Anscombe s quartet, antiderivative, 200. bar charts for exercise, for expenses, Barnsley fern, drawing,
Index Symbols + (addition operator), 2 {} (curly brackets), to define a set, 122 δ (delta), 184 / (division operator), 2 ε (epsilon), 192, 197 199 == (equality operator), 124 e (Euler s number), 179 **
More informationWarm-Up Exercises. Find the x-intercept and y-intercept 1. 3x 5y = 15 ANSWER 5; y = 2x + 7 ANSWER ; 7
Warm-Up Exercises Find the x-intercept and y-intercept 1. 3x 5y = 15 ANSWER 5; 3 2. y = 2x + 7 7 2 ANSWER ; 7 Chapter 1.1 Graph Quadratic Functions in Standard Form A quadratic function is a function that
More informationLECTURE 22. Numerical and Scientific Packages
LECTURE 22 Numerical and Scientific Packages NUMERIC AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that extend
More informationMEI Desmos Tasks for AS Pure
Task 1: Coordinate Geometry Intersection of a line and a curve 1. Add a quadratic curve, e.g. y = x² 4x + 1 2. Add a line, e.g. y = x 3 3. Select the points of intersection of the line and the curve. What
More informationQUADRATIC AND CUBIC GRAPHS
NAME SCHOOL INDEX NUMBER DATE QUADRATIC AND CUBIC GRAPHS KCSE 1989 2012 Form 3 Mathematics Working Space 1. 1989 Q22 P1 (a) Using the grid provided below draw the graph of y = -2x 2 + x + 8 for values
More informationEuler s Method with Python
Euler s Method with Python Intro. to Differential Equations October 23, 2017 1 Euler s Method with Python 1.1 Euler s Method We first recall Euler s method for numerically approximating the solution of
More informationLab 2: Introducing XPPAUT
Lab 2: Introducing XPPAUT In biological applications it is quite rare that the solutions of the appropriate differential equations can be obtained using paper and pencil. Thus we typically need to use
More informationFront page. UNIVERSITY OF OSLO Faculty of mathematics and natural sciences
Front page UNIVERSITY OF OSLO Faculty of mathematics and natural sciences Examination in: IN1900/INF1100 Introduction to programming for scientific applications Day of examination: December 18th 2017 Examination
More informationComputer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont)
CP Lect 5 slide 1 Monday 2 October 2017 Computer Programming: Skills & Concepts (CP) arithmetic, if and booleans (cont) Cristina Alexandru Monday 2 October 2017 Last Lecture Arithmetic Quadratic equation
More informationPS6-DCT-Soln-correction
PS6-DCT-Soln-correction Unknown Author March 18, 2014 Part I DCT: Discrete Cosine Transform DCT is a linear map A R N N such that the N real numbers x 0,..., x N 1 are transformed into the N real numbers
More informationEXAMPLE. 1. Enter y = x 2 + 8x + 9.
VI. FINDING INTERCEPTS OF GRAPHS As we have seen, TRACE allows us to find a specific point on the graph. Thus TRACE can be used to solve a number of important problems in algebra. For example, it can be
More informationProject assignment: Particle-based simulation of transport by ocean currents
Project assignment: Particle-based simulation of transport by ocean currents Tor Nordam, Jonas Blomberg Ghini, Jon Andreas Støvneng 1 Introduction It is probably well known that the Norwegian Meteorological
More informationUNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER
UNIVERSITI TEKNIKAL MALAYSIA MELAKA FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER FAKULTI KEJURUTERAAN ELEKTRONIK DAN KEJURUTERAAN KOMPUTER BENC 2113 DENC ECADD 2532 ECADD LAB SESSION 6/7 LAB
More informationERTH2020 Introduction to Geophysics
ERTH2020 Practical:: Introduction to Python Page 1 ERTH2020 Introduction to Geophysics 2018 Practical 1: Introduction to scientific programming using Python, and revision of basic mathematics Purposes
More information2. From General Form: y = ax 2 + bx + c # of x-intercepts determined by the, D =
Alg2H 5-3 Using the Discriminant, x-intercepts, and the Quadratic Formula WK#6 Lesson / Homework --Complete without calculator Read p.181-p.186. Textbook required for reference as well as to check some
More informationPartial Differential Equations II: 2D Laplace Equation on 5x5 grid
Partial Differential Equations II: 2D Laplace Equation on 5x5 grid Sam Sinayoko Numerical Methods 5 Contents 1 Learning Outcomes 2 2 Introduction 3 3 Laplace equation in 2D 3 4 Discretisation 3 4.1 Meshing:
More informationQuadratic Equations. Learning Objectives. Quadratic Function 2. where a, b, and c are real numbers and a 0
Quadratic Equations Learning Objectives 1. Graph a quadratic function using transformations. Identify the vertex and axis of symmetry of a quadratic function 3. Graph a quadratic function using its vertex,
More informationIntroduction to Octave/Matlab. Deployment of Telecommunication Infrastructures
Introduction to Octave/Matlab Deployment of Telecommunication Infrastructures 1 What is Octave? Software for numerical computations and graphics Particularly designed for matrix computations Solving equations,
More informationMAS212 Scientific Computing and Simulation
MAS212 Scientific Computing and Simulation Dr. Sam Dolan School of Mathematics and Statistics, University of Sheffield Autumn 2017 http://sam-dolan.staff.shef.ac.uk/mas212/ G18 Hicks Building s.dolan@sheffield.ac.uk
More informationThis Worksheet shows you several ways to start using Enthought s distribution of Python!
This Worksheet shows you several ways to start using Enthought s distribution of Python! Start the Terminal application by Selecting the Utilities item from the Go menu located at the top of the screen
More informationC3 Numerical methods
Verulam School C3 Numerical methods 138 min 108 marks 1. (a) The diagram shows the curve y =. The region R, shaded in the diagram, is bounded by the curve and by the lines x = 1, x = 5 and y = 0. The region
More informationAn introduction to interpolation and splines
An introduction to interpolation and splines Kenneth H. Carpenter, EECE KSU November 22, 1999 revised November 20, 2001, April 24, 2002, April 14, 2004 1 Introduction Suppose one wishes to draw a curve
More informationThe Bisection Method versus Newton s Method in Maple (Classic Version for Windows)
The Bisection Method versus (Classic Version for Windows) Author: Barbara Forrest Contact: baforres@uwaterloo.ca Copyrighted/NOT FOR RESALE version 1.1 Contents 1 Objectives for this Lab i 2 Approximate
More informationUnit 3, Lesson 3.1 Creating and Graphing Equations Using Standard Form
Unit 3, Lesson 3.1 Creating and Graphing Equations Using Standard Form Imagine the path of a basketball as it leaves a player s hand and swooshes through the net. Or, imagine the path of an Olympic diver
More informationFirst of all, we need to know what it means for a parameterize curve to be differentiable. FACT:
CALCULUS WITH PARAMETERIZED CURVES In calculus I we learned how to differentiate and integrate functions. In the chapter covering the applications of the integral, we learned how to find the length of
More informationENGR 102 Engineering Lab I - Computation
ENGR 102 Engineering Lab I - Computation Week 07: Arrays and Lists of Data Introduction to Arrays In last week s lecture, 1 we were introduced to the mathematical concept of an array through the equation
More informationpython 01 September 16, 2016
python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7
More informationUsing the Matplotlib Library in Python 3
Using the Matplotlib Library in Python 3 Matplotlib is a Python 2D plotting library that produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.
More informationPython for Scientists
High level programming language with an emphasis on easy to read and easy to write code Includes an extensive standard library We use version 3 History: Exists since 1991 Python 3: December 2008 General
More information2 Getting Started with Numerical Computations in Python
1 Documentation and Resources * Download: o Requirements: Python, IPython, Numpy, Scipy, Matplotlib o Windows: google "windows download (Python,IPython,Numpy,Scipy,Matplotlib" o Debian based: sudo apt-get
More information1.1 Graphing Quadratic Functions (p. 2) Definitions Standard form of quad. function Steps for graphing Minimums and maximums
1.1 Graphing Quadratic Functions (p. 2) Definitions Standard form of quad. function Steps for graphing Minimums and maximums Quadratic Function A function of the form y=ax 2 +bx+c where a 0 making a u-shaped
More informationDirection Fields; Euler s Method
Direction Fields; Euler s Method It frequently happens that we cannot solve first order systems dy (, ) dx = f xy or corresponding initial value problems in terms of formulas. Remarkably, however, this
More informationNumerical Methods in Engineering Sciences
Numerical Methods in Engineering Sciences Lecture 1: Brief introduction to MATLAB Pablo Antolin pablo.antolinsanchez@unipv.it October 29th 2013 How many of you have used MATLAB before? How many of you
More informationEXERCISE SET 10.2 MATD 0390 DUE DATE: INSTRUCTOR
EXERCISE SET 10. STUDENT MATD 090 DUE DATE: INSTRUCTOR You have studied the method known as "completing the square" to solve quadratic equations. Another use for this method is in transforming the equation
More informationoperator overloading algorithmic differentiation the class DifferentialNumber operator overloading
operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining
More informationMathematical Programming
Mathematical Programming Example #9-1. Minimize the following problem related to the linear programming. Minimize: f(x, y) = x + 4y Subject to: 3x + y 6 x + 2y 4 y 3 where x TA: Junhee Lee Python Code
More informationMath 1: Solutions to Written Homework 1 Due Friday, October 3, 2008
Instructions: You are encouraged to work out solutions to these problems in groups! Discuss the problems with your classmates, the tutors and/or the instructors. After working doing so, please write up
More informationChE 400: Applied Chemical Engineering Calculations Tutorial 6: Numerical Solution of ODE Using Excel and Matlab
ChE 400: Applied Chemical Engineering Calculations Tutorial 6: Numerical Solution of ODE Using Excel and Matlab Tutorial 6: Numerical Solution of ODE Gerardine G. Botte This handout contains information
More informationPhys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3
Phys 60441 Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3 Tim O Brien Room 3.214 Alan Turing Building tim.obrien@manchester.ac.uk Tuples Lists and strings are examples of sequences.
More informationThe SciPy Stack. Jay Summet
The SciPy Stack Jay Summet May 1, 2014 Outline Numpy - Arrays, Linear Algebra, Vector Ops MatPlotLib - Data Plotting SciPy - Optimization, Scientific functions TITLE OF PRESENTATION 2 What is Numpy? 3rd
More informationLecture 8. Divided Differences,Least-Squares Approximations. Ceng375 Numerical Computations at December 9, 2010
Lecture 8, Ceng375 Numerical Computations at December 9, 2010 Computer Engineering Department Çankaya University 8.1 Contents 1 2 3 8.2 : These provide a more efficient way to construct an interpolating
More information2. Solve for x when x < 22. Write your answer in interval notation. 3. Find the distance between the points ( 1, 5) and (4, 3).
Math 6 Practice Problems for Final. Find all real solutions x such that 7 3 x = 5 x 3.. Solve for x when 0 4 3x
More informationCS110D: PROGRAMMING LANGUAGE I
CS110D: PROGRAMMING LANGUAGE I Computer Science department Lecture 7&8: Methods Lecture Contents What is a method? Static methods Declaring and using methods Parameters Scope of declaration Overloading
More informationChapter 5 : Informatics Practices. Class XII ( As per CBSE Board) Numpy - Array. New Syllabus Visit : python.mykvs.in for regular updates
Chapter 5 : Informatics Practices Class XII ( As per CBSE Board) Numpy - Array New Syllabus 2019-20 NumPy stands for Numerical Python.It is the core library for scientific computing in Python. It consist
More informationAlgebra II Chapter 5
Algebra II Chapter 5 5.1 Quadratic Functions The graph of a quadratic function is a parabola, as shown at rig. Standard Form: f ( x) = ax2 + bx + c vertex: b 2a, f b 2a a < 0 graph opens down a > 0 graph
More informationIntroduction to Computational Models Using Python
Introduction to Computational Models Using Python Slides 04 Department of Computer Science College of Computing and Software Engineering Kennesaw State University June, 2016 Lists A list in Python is simply
More informationFall 2015 Math 337. Basic MatLab
Fall 215 Math 337 Basic MatLab MatLab is a powerful software created by MathWorks, which is used extensively in mathematics, engineering, and the sciences. It has powerful numerical and graphic capabilities,
More informationGraphing and Equations
Graphing and Equations Plotting Functions (Graphing) Let's see how to plot the graphs of functions. If we want to graph the function f(x) on the interval [a,b] then we type in: plot(f(x), x=a..b) That
More informationMATLAB Examples. Interpolation and Curve Fitting. Hans-Petter Halvorsen
MATLAB Examples Interpolation and Curve Fitting Hans-Petter Halvorsen Interpolation Interpolation is used to estimate data points between two known points. The most common interpolation technique is Linear
More informationPART 1 PROGRAMMING WITH MATHLAB
PART 1 PROGRAMMING WITH MATHLAB Presenter: Dr. Zalilah Sharer 2018 School of Chemical and Energy Engineering Universiti Teknologi Malaysia 23 September 2018 Programming with MATHLAB MATLAB Environment
More informationA more generalized coordinate transformation approach for grisms
Instrument Science Report WFC3 2017-01 A more generalized coordinate transformation approach for grisms Nor Pirzkal, R. Ryan January 5, 2017 ABSTRACT Current HST configuration files for the NICMOS, ACS
More informationPhysicsAndMathsTutor.com
Question Answer Marks Guidance 1 (i) y = (x + 5)(x + )(x 3) or for y = (x + 5)(x + )(x 3/) or allow f(x) = instead of y = y = (x + 5)(x + )( x 3/) (x + 5)(x + )(x 3) with no equation or (x + 5)(x + )(x
More informationFunctions of Several Variables
Jim Lambers MAT 280 Spring Semester 2009-10 Lecture 2 Notes These notes correspond to Section 11.1 in Stewart and Section 2.1 in Marsden and Tromba. Functions of Several Variables Multi-variable calculus
More informationLab 4: Structured Programming I
4.1 Introduction Lab 4: Structured Programming I Lab this week is going to focus on selective structures and functions. 4.2 Resources The additional resources required for this assignment include: 0 Books:
More informationERTH3021 Exploration and Mining Geophysics
ERTH3021 Exploration and Mining Geophysics Practical 1: Introduction to Scientific Programming using Python Purposes To introduce simple programming skills using the popular Python language. To provide
More informationFriday, 11 January 13. Interpolation
Interpolation Interpolation Interpolation is not a branch of mathematic but a collection of techniques useful for solving computer graphics problems Basically an interpolant is a way of changing one number
More informationRemember Java Data Types
1.00 Lecture 19 October 24, 2005 Numerical Methods: Root Finding Remember Java Data Types Size Type (bits) Range byte 8-128 to 127 short 16-32,768 to 32,767 int 32-2,147,483,648 to 2,147,483,647 long 64-9,223,372,036,854,775,808L
More informationTHE TANGENT PLANE 6.1 INTRODUCTION TO THE TANGENT PLANE CHAPTER 6:
CHAPTER 6: THE TANGENT PLANE 6.1 INTRODUCTION TO THE TANGENT PLANE The following diagram contains the graph of the function y = x 2 and the graph of its tangent line at the point (1, 1) With these graphs,
More informationCSC Advanced Scientific Computing, Fall Numpy
CSC 223 - Advanced Scientific Computing, Fall 2017 Numpy Numpy Numpy (Numerical Python) provides an interface, called an array, to operate on dense data buffers. Numpy arrays are at the core of most Python
More informationmathcad_homework_in_matlab.m Dr. Dave S#
Table of Contents Basic calculations - solution to quadratic equation: a*x^ + b*x + c = 0... 1 Plotting a function with automated ranges and number of points... Plotting a function using a vector of values,
More informationPython in Economics and Finance
Python in Economics and Finance Part 2 John Stachurski, ANU June 2014 Topics Data types OOP Iteration Functions NumPy / SciPy Matplotlib Data Types We have already met several native Python data types»>
More informationWeek Two. Arrays, packages, and writing programs
Week Two Arrays, packages, and writing programs Review UNIX is the OS/environment in which we work We store files in directories, and we can use commands in the terminal to navigate around, make and delete
More informationModule1: Numerical Solution of Ordinary Differential Equations. Lecture 6. Higher order Runge Kutta Methods
Module1: Numerical Solution of Ordinary Differential Equations Lecture 6 Higher order Runge Kutta Methods Keywords: higher order methods, functional evaluations, accuracy Higher order Runge Kutta Methods
More informationDatenanalyse (PHY231) Herbstsemester 2017
Datenanalyse (PHY231) Herbstsemester 2017 A short pylab repetition 22/09/2017 An important part of the exercises for this course involves programming in python / pylab. We assume that you have completed
More informationProperties of Quadratic functions
Name Today s Learning Goals: #1 How do we determine the axis of symmetry and vertex of a quadratic function? Properties of Quadratic functions Date 5-1 Properties of a Quadratic Function A quadratic equation
More informationEpisode 8 Matplotlib, SciPy, and Pandas. We will start with Matplotlib. The following code makes a sample plot.
Episode 8 Matplotlib, SciPy, and Pandas Now that we understand ndarrays, we can start using other packages that utilize them. In particular, we're going to look at Matplotlib, SciPy, and Pandas. Matplotlib
More informationSunpy Python for Solar Physics Juan Carlos Martínez Oliveros
Sunpy Python for Solar Physics Juan Carlos Martínez Oliveros In the beginning (ENIAC) Evolution Evolution Evolution Introduction The SunPy project is an effort to create an opensource software library
More informationSparse Grids. Lab 1. Discretization
Lab 1 Sparse Grids Lab Objective: Sparse Grids are an important tool when dealing with highdimensional problems. Computers operate in discrete space, not in continuous space. It is important to choose
More information3x - 5 = 22 4x - 12 = 2x - 9
3. Algebra Solving Equations ax + b = cx + d Algebra is like one big number guessing game. I m thinking of a number. If you multiply it by 2 and add 5, you get 21. 2x + 5 = 21 For a long time in Algebra
More informationSkills Quiz - Python Edition Solutions
'XNH8QLYHUVLW\ (GPXQG73UDWW-U6FKRRORI(QJLQHHULQJ EGR 103L Fall 2017 Skills Quiz - Python Edition Solutions Michael R. Gustafson II Name (please print): NetID (please print): In keeping with the Community
More informationIntroduction to Simulink
Introduction to Simulink There are several computer packages for finding solutions of differential equations, such as Maple, Mathematica, Maxima, MATLAB, etc. These systems provide both symbolic and numeric
More informationIntroductory Scientific Computing with Python
Introductory Scientific Computing with Python More plotting, lists and FOSSEE Department of Aerospace Engineering IIT Bombay SciPy India, 2015 December, 2015 FOSSEE (FOSSEE IITB) Interactive Plotting 1
More information1.00 Lecture 19. Numerical Methods: Root Finding
1.00 Lecture 19 Numerical Methods: Root Finding short int Remember Java Data Types Type byte long float double char boolean Size (bits) 8 16 32 64 32 64 16 1-128 to 127-32,768 to 32,767-2,147,483,648 to
More informationHandout 4 - Interpolation Examples
Handout 4 - Interpolation Examples Middle East Technical University Example 1: Obtaining the n th Degree Newton s Interpolating Polynomial Passing through (n+1) Data Points Obtain the 4 th degree Newton
More informationSampling from distributions
Sampling from distributions December 17, 2015 1 Sampling from distributions Now that we are able to sample equally distributed (pseudo-)random numbers in the interval [1, 0), we are now able to sample
More information