operator overloading algorithmic differentiation the class DifferentialNumber operator overloading
|
|
- Owen Andrews
- 5 years ago
- Views:
Transcription
1 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator MCS 507 Lecture 26 Mathematical, Statistical and Scientific Software Jan Verschelde, 25 October 2013 Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
2 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
3 computing with differential numbers A differential number is a tuple df = (f, f ) of two doubles where f is the evaluated derivative of f. The operator overloading encodes the elementary derivative rules for addition, subtraction, multiplication, and division of two real numbers. As we evaluate any expression written in these four elementary operations, we also compute its derivative. With a Python script we illustrate the forward mode of algorithmic differentiation. Reference: section (c) on computing with differential numbers of Introduction to Numerical Analysis, pages 7 to 10, by Arnold Neuimaier, Cambridge Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
4 encoding differentiation rules Let df = (f, f ) and dg = (g, g ), where f and g are dependent on one single variable x. The four basic elementary operations are +,, and /, defined as follows: df + dg = (f, f ) + (g, g ) = (f + g, f + g ) df dg = (f, f ) (g, g ) = (f g, f g ) df dg = (f, f ) (g, g ) = (f g, f g + f g ) df/dg = (f, f )/(g, g ) = (f/g,(f (f/g) g )/g) Constants and the independent variable as differential numbers: Any constant c (independent of x) is represented as (c, 0). The independent variable x is represented as (x, 1). Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
5 evaluating derivatives without explicit formulas Consider f(x) = (x 1)(x + 3) x + 2 (f, f ) ± (g, g ) = (f ± g, f ± g ), (f, f ) (g, g ) = (f g, f g + f g ), (f, f )/(g, g ) = (f/g,(f (f/g) g )/g). at x 0 = 3. Recall the rules: We substitute the differential number (3, 1) in f : (f(3), f (3)) = ((3, 1) 1) ((3, 1) + 3) f((3, 1)) = (3, 1) + 2 (2, 1) (6, 1) = (5, 1) (12, 8) = (5, 1) = (2.4,( )/5) = (2.4, 1.12) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
6 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
7 the data attribute of the class class DifferentialNumber(object): A differential number is a tuple df = (f, f ) of two doubles where f is the evaluated derivative of f. def init (self, xv, xp=1): Initializes a differential number to the tuple (xv, xp). self.val = float(xv) self.der = float(xp) By default, DifferentialNumber(x) for any x is (x, 1). Note the explicit conversion to type float. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
8 the string respresentation A differential number (f, f ) is represented as a tuple. def str (self): Returns the tuple representation of the differential number. return str((self.val, self.der)) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
9 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
10 adding differential numbers The rule df + dg = (f, f ) + (g, g ) = (f + g, f + g ) is implemented by overriding the builtin operator + defined by add. The self refers to the first operand, while the second operand is given by the other argument. def add (self, other): Defines the addition of two differential numbers. return DifferentialNumber(self.val + other.val, \ self.der + other.der) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
11 dealing with cases like x def add (self, other): Defines the addition of two differential numbers. if isinstance(other, float): return DifferentialNumber \ (self.val + other, self.der) else: return DifferentialNumber \ (self.val + other.val, \ self.der + other.der) For x we must do DifferentialNumber(2.0, 0.0) + x. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
12 subtraction of two differential numbers The operator is defined by the sub () method: def sub (self, other): Defines the subtraction of two differential numbers. if isinstance(other, float): return DifferentialNumber \ (self.val - other, self.der) else: return DifferentialNumber \ (self.val - other.val, \ self.der - other.der) This implements the rule df dg = (f, f ) (g, g ) = (f g, f g ) and also deals with the case g = (c, 0). Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
13 multiplying two differential numbers The rule (f, f ) (g, g ) = (f g, f g + f g ) is implemented by overriding the method mul (): def mul (self, other): Defines the product of two differential numbers. return DifferentialNumber \ (self.val*other.val, \ self.der*other.val + \ self.val*other.der) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
14 multiplication with a constant For a constant c: (f, f ) (c, 0) = (f c, f c). def mul (self, other): Defines the product of two differential numbers. if isinstance(other, float): return DifferentialNumber \ (self.val*other, self.der*other) else: return DifferentialNumber (self.val*other.val, \ self.der*other.val + \ self.val*other.der) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
15 dividing two differential numbers We override the div () method to define division. Coding the rule (f, f )/(g, g ) = (f/g,(f (f/g) g )/g): def div (self, other): Defines the division of two differential numbers. val = self.val/other.val return DifferentialNumber \ (val, (self.der \ - val*other.der)/other.val) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
16 dividing by a constant For a constant c: (f, f )/(c, 0) = (f/c, f /c). def div (self, other): Defines the division of two differential numbers. if isinstance(other, float): return DifferentialNumber \ (self.val/other, self.der/other) else: val = self.val/other.val return DifferentialNumber \ (val, (self.der \ - val*other.der)/other.val) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
17 the main test program def main(): Test on the expression ((x-1)*(x+3))/(x+2). dfx = DifferentialNumber(3, 1) fun = lambda x: ((x-1.0)*(x+3.0))/(x+2.0) print ((x-1)*(x+3))/(x+2) at, dfx, : dfy = fun(dfx) print dfy if name == " main ": main() Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
18 running the test $ python differential_numbers.py ((x-1)*(x+3))/(x+2) at (3.0, 1.0) : (2.4, ) $ Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
19 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
20 double double arithmetic in Python Recall what we did in the second half of lecture 25: 1 We looked at a C program to use the double double arithmetic of the QD library to apply Newton s method to approximate 2. 2 We defined the module doubledouble that exports the basic functionality of the C interface of the QD library to perform double double arithmetic in Python. In Python, a double double was seen as a tuple of two doubles. The arithmetic was performed by methods that took 4 arguments: the high and low parts of both operators. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
21 operator overloading To add two double doubles x and y, instead of z = doubledouble.add(x[0],x[1],y[0],y[1]) we would like to write z = x + y. We will define the class DoubleDouble() and export the method add. Defining the method add allows to use the + operator on any two elements of the class DoubleDouble. The + is a binary operator: 1 the self is the first operand of +, 2 other is the second operand of +. The definition starts with def add (self,other):. Subtraction, multiplication, and division are defined respectively by sub, mul, and div. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
22 data attributes of the class DoubleDouble Importing the module doubledouble that wraps some of the basic functionality of the QD library: import doubledouble class DoubleDouble(): Wraps some of the functionality of the QD library to perform double double arithmetic. def init (self, hi=0.0, lo=0.0): A double double consists of a high and a low part. self.high = hi self.low = lo Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
23 string representations and deep copy def str (self): Returns the string representation of a double double. return doubledouble.str(self.high, self.low) def repr (self): Returns the representation of a double double. return self. str () def copy(self): Returns a copy of the double double. return DoubleDouble(self.high, self.low) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
24 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
25 addition and subtraction def add (self, other): Returns the sum of two double doubles. z = doubledouble.add(self.high, self.low, \ other.high, other.low) return DoubleDouble(z[0], z[1]) def sub (self, other): Returns the difference of self and the other. z = doubledouble.sub(self.high, self.low, \ other.high, other.low) return DoubleDouble(z[0], z[1]) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
26 multiplication and division def mul (self, other): Returns the product of two double doubles. z = doubledouble.mul(self.high, self.low, \ other.high, other.low) return DoubleDouble(z[0], z[1]) def div (self, other): Returns the division of self by the other. z = doubledouble.div(self.high, self.low, \ other.high, other.low) return DoubleDouble(z[0], z[1]) Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
27 computing powers To compute x**5, we overload the pow method: def pow (self,n): Returns self to the power n. z = self.copy() for i in range(1,n): z = z*self return z Note: it is more efficient to wrap c_dd_npwr(). Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
28 a basic test on the arithmetic def test(): Basic test on arithmetical operations. hi = lo = e-17 x = DoubleDouble(hi, lo) # defines the sqrt(2) print x = sqrt(2) =, str(x) y = x**2 print x*x =, y z = y/x print x*x/x =, z u = x+x print x+x =, u two = DoubleDouble(2.0) print 2*x =, two*x v = u-x print x+x-x =, v Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
29 running the test Adding to the end of double_double.py the line if name ==" main ": test() so we can run $ python double_double.py x = sqrt(2) = x*x = x*x/x = x+x = *x = x+x-x = Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
30 Newton s method for 2 def newton4sqrt2(): Applies Newton s method to approximate sqrt(2). x = DoubleDouble(2.0) print step 0 :, x for i in range(1,9): z = x**2 z = z + DoubleDouble(2.0) z = z/x z = DoubleDouble(0.5)*z x = z.copy() print step, i, :, x Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
31 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
32 a motivating example for interval arithmetic Problem: Evaluate f(x, y) = ( x 2 )y 6 + x 2 (11x 2 y 2 121y 4 2) + 5.5y 8 + x/(2y) at (77617, 33096). An example of Stefano Taschini: Interval Arithmetic: Python Implementation and Applications. In the Proceedings of the 7th Python in Science Conference (SciPy 2008). Let us evaluate this expression with double doubles... Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
33 evaluating an expression print checking the motivating interval arithmetic example f = lambda x,y: (DoubleDouble(333.75) - x**2)*y**6 \ + x**2*(doubledouble(11)*x**2*y**2 \ - DoubleDouble(121)*y**4 - DoubleDouble(2)) \ + DoubleDouble(5.5)*y**8 + x/(doubledouble(2)*y); a = 77617; b = z = f(doubledouble(a),doubledouble(b)) # to check the answer with SymPy : import sympy as sp x,y = sp.var( x,y ) g = (sp.rational(33375)/100 - x**2)*y**6 \ + x**2*(11*x**2*y**2-121*y**4-2) \ + sp.rational(55)/10*y**8 \ + sp.rational(1)*x/(2*y); print evaluating, g, at, (a,b) e = sp.subs(g,(x,y),(a,b)).doit() Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
34 script continued and running the code e15 = e.evalf(15) print numerical value :, z print exact value :, e, ~, e15 print error :, abs(e15 - z.high) We run the script as follows: $ python double_double_eval.py checking the motivating interval arithmetic example evaluating x**2*(11*x**2*y**2-121*y**4-2) + x/(2*y) + 1 numerical value : e+00 exact value : /66192 ~ error : $ Exercise: wrap quad doubles for an accurate evaluation. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
35 operator overloading 1 Computing with Differential Numbers algorithmic differentiation the class DifferentialNumber operator overloading 2 Computing with Double Doubles the class DoubleDouble defining +, -, *, and / expression evaluation 3 Wrapping C Code with SWIG swig = simplified wrapper and interface generator Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
36 Simplified Wrapper and Interface Generator Available at SWIG is a software development tool that connects programs written in C and C++ with high-level programming languages. SWIG is used with different types of target languages including scripting languages such as Perl, PHP, Python, Tcl and Ruby. SWIG is most commonly used to create high-level interpreted or compiled programming environments, user interfaces, and as a tool for testing and prototyping C/C++ software. SWIG is typically used to parse C/C++ interfaces and generate the glue code required for the above target languages to call into the C/C++ code. SWIG is free software and the code that SWIG generates is compatible with both commercial and non-commercial projects. We will work out the example of the tutorial. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
37 example.c from #include <time.h> double My_variable = 3.0; int fact(int n) { if (n <= 1) return 1; else return n*fact(n-1); } int my_mod(int x, int y) { return (x%y); } char *get_time() { time_t ltime; time(<ime); return ctime(<ime); } Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
38 example.i from %module example %{ /* put header files here or function declarations */ extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); %} extern double My_variable; extern int fact(int n); extern int my_mod(int x, int y); extern char *get_time(); Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
39 the makefile The makefile defines the compilation instructions, on RHEL: PYTHON=/usr/include/python2.6 example: swig -python example.i gcc -c -fpic example.c example_wrap.c -I$(PYTHON) gcc -shared example.o example_wrap.o \ -o _example.so Executing: $ make example swig -python example.i gcc -c -fpic example.c example_wrap.c -I/usr/include/python gcc -shared example.o example_wrap.o -o _example.so $ Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
40 input and output files Two input files: 1 example.c with C code, 2 example.i is the interface file. To compile successfully, we must know 1 the location of the Python header files, 2 proper linking options, e.g.: -framework Python on Mac. Four output files: 1 example_wrap.c generated C code, 2 example_wrap.o compiled object file, 3 _example.so shared object file, and 4 example.py Python code for wrapper. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
41 Summary + Exercises Operator overloading makes double double arithmetic natural. Another benefit of operator overloading is to add properties of the computed results, e.g.: derivatives, roundoff errors, operation counts. 1 Extend the class DifferentialNumber so it works for expressions in two variables and a differential number df is (f, f x, f y ), where f x is the derivative with respect to the first variable and f y is the derivative with respect to the second variable. 2 Extend the class DifferentialNumber to compute also the second derivative and a differential number df is (f, f, f ). 3 Wrap the basic operations for quad double arithmetic of the QD library and make the class QuadDouble. Use the class to evaluate the expression of the motivating example for interval arithmetic. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
42 some more exercises 4 We estimate the roundoff error of an arithmetical operation, for {+,,,/} and floating-point numbers x and y as x y = (x y)(1 + ǫ), where is the floating-point version of and 0 ǫ < ǫ mach, for the machine precision ǫ mach. The roundoff error is bounded by x y ǫ mach. For accumulated roundoff: x 0 x 1 x }{{ n (x } 0 x 1 x n )(1 + ǫ 1 + ǫ ǫ n + ), n operations Truncating higher-order terms, the accumulated roundoff on n operations is estimated by x 0 x 1 x n nǫ mach. Define a class NumericalFloat, overriding +,,, and /, to also compute the upper bound on the roundoff for each operation. The accumulated roundoff is stored as an extra data attribute with each float. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
43 and some more exercises 4 Using inheritance extend the class DoubleDouble with an extra field count to count the number of arithmetical operations performed to compute a double double. For example, if two constants have counts m and n, their sum has count m + n. 5 Use SWIG to wrap the dd_sqrt() function of lecture 25. Project Two due Friday 1 November at 9AM. Scientific Software (MCS 507 L-26) operator overloading 25 October / 43
Floating-Point Arithmetic
Floating-Point Arithmetic 1 Numerical Analysis a definition sources of error 2 Floating-Point Numbers floating-point representation of a real number machine precision 3 Floating-Point Arithmetic adding
More informationInterval Arithmetic. MCS 507 Lecture 29 Mathematical, Statistical and Scientific Software Jan Verschelde, 28 October 2011
Naive Arithmetic 1 2 Naive 3 MCS 507 Lecture 29 Mathematical, Statistical and Scientific Software Jan Verschelde, 28 October 2011 Naive Arithmetic 1 2 Naive 3 an expression Naive Problem: Evaluate f(x,
More informationdifferentiation techniques
differentiation techniques 1 Callable Objects delayed execution of stored code 2 Numerical and Symbolic Differentiation numerical approximations for the derivative storing common code in a parent class
More informationOperator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum
Operator Overloading 1 OOP to count Flops a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum 2 Quaternions hypercomplex numbers application in computer
More informationcallback, iterators, and generators
callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton
More informationCreating a new data type
Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building
More informationAstronomical Data Analysis with Python
Astronomical Data Analysis with Python Lecture 8 Yogesh Wadadekar NCRA-TIFR July August 2010 Yogesh Wadadekar (NCRA-TIFR) Topical course 1 / 27 Slides available at: http://www.ncra.tifr.res.in/ yogesh/python_course_2010/
More informationErrors in Computation
Theory of Errors Content Errors in computation Absolute Error Relative Error Roundoff Errors Truncation Errors Floating Point Numbers Normalized Floating Point Numbers Roundoff Error in Floating Point
More informationRunning Cython. overview hello world with Cython. experimental setup adding type declarations cdef functions & calling external functions
Running Cython 1 Getting Started with Cython overview hello world with Cython 2 Numerical Integration experimental setup adding type declarations cdef functions & calling external functions 3 Using Cython
More informationPython Programming Exercises 1
Python Programming Exercises 1 Notes: throughout these exercises >>> preceeds code that should be typed directly into the Python interpreter. To get the most out of these exercises, don t just follow them
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 informationLists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists
Lists and Loops 1 Lists in Python defining lists lists as queues and stacks inserting and removing membership and ordering lists 2 Loops in Python for and while loops the composite trapezoidal rule MCS
More informationDefining Functions. turning expressions into functions. writing a function definition defining and using modules
Defining Functions 1 Lambda Functions turning expressions into functions 2 Functions and Modules writing a function definition defining and using modules 3 Computing Series Developments exploring an example
More informationLists and Loops. browse Python docs and interactive help
Lists and Loops 1 Help in Python browse Python docs and interactive help 2 Lists in Python defining lists lists as queues and stacks inserting and removing membership and ordering lists 3 Loops in Python
More informationCSC312 Principles of Programming Languages : Functional Programming Language. Copyright 2006 The McGraw-Hill Companies, Inc.
CSC312 Principles of Programming Languages : Functional Programming Language Overview of Functional Languages They emerged in the 1960 s with Lisp Functional programming mirrors mathematical functions:
More informationQuad Doubles on a GPU
Quad Doubles on a GPU 1 Floating-Point Arithmetic floating-point numbers quad double arithmetic quad doubles for use in CUDA programs 2 Quad Double Square Roots quad double arithmetic on a GPU a kernel
More informationWeek 2: Console I/O and Operators Arithmetic Operators. Integer Division. Arithmetic Operators. Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.
Week 2: Console I/O and Operators Gaddis: Chapter 3 (2.14,3.1-6,3.9-10,5.1) CS 1428 Fall 2014 Jill Seaman 1 2.14 Arithmetic Operators An operator is a symbol that tells the computer to perform specific
More informationArbitrary Precision and Symbolic Calculations
Arbitrary Precision and Symbolic Calculations K. 1 1 Department of Mathematics 2018 Sympy There are several packages for Python that do symbolic mathematics. The most prominent of these seems to be Sympy.
More informationSoftware II: Principles of Programming Languages. Why Expressions?
Software II: Principles of Programming Languages Lecture 7 Expressions and Assignment Statements Why Expressions? Expressions are the fundamental means of specifying computations in a programming language
More informationChapter Two MIPS Arithmetic
Chapter Two MIPS Arithmetic Computer Organization Review Binary Representation Used for all data and instructions Fixed size values: 8, 16, 32, 64 Hexadecimal Sign extension Base and virtual machines.
More informationList Comprehensions and Simulations
List Comprehensions and Simulations 1 List Comprehensions examples in the Python shell zipping, filtering, and reducing 2 Monte Carlo Simulations testing the normal distribution the Mean Time Between Failures
More informationturning expressions into functions symbolic substitution, series, and lambdify
Defining Functions 1 Lambda Functions turning expressions into functions symbolic substitution, series, and lambdify 2 Functions and Modules writing a function definition defining and using modules where
More informationPHCpack, phcpy, and Sphinx
PHCpack, phcpy, and Sphinx 1 the software PHCpack a package for Polynomial Homotopy Continuation polyhedral homotopies the Python interface phcpy 2 Documenting Software with Sphinx Sphinx generates documentation
More informationUnit 3. Operators. School of Science and Technology INTRODUCTION
INTRODUCTION Operators Unit 3 In the previous units (unit 1 and 2) you have learned about the basics of computer programming, different data types, constants, keywords and basic structure of a C program.
More informationIntroduction to Programming II W4260. Lecture 2
Introduction to Programming II W4260 Lecture 2 Overview Storing Data Basic types Arrays Controlling the flow of execution Loops (for, while) Ifthenelse Operators Arithmetic, relational, logical Functions
More informationAnnouncements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop
Announcements Lab Friday, 1-2:30 and 3-4:30 in 26-152 Boot your laptop and start Forte, if you brought your laptop Create an empty file called Lecture4 and create an empty main() method in a class: 1.00
More informationArithmetic and Bitwise Operations on Binary Data
Arithmetic and Bitwise Operations on Binary Data CSCI 2400: Computer Architecture ECE 3217: Computer Architecture and Organization Instructor: David Ferry Slides adapted from Bryant & O Hallaron s slides
More informationlambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions
Outline 1 Guessing Secrets functions returning functions oracles and trapdoor functions 2 anonymous functions lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions
More informationFloating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754
Floating Point Puzzles Topics Lecture 3B Floating Point IEEE Floating Point Standard Rounding Floating Point Operations Mathematical properties For each of the following C expressions, either: Argue that
More informationJim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 4
Jim Lambers ENERGY 211 / CME 211 Autumn Quarter 2008-09 Programming Project 4 This project is due at 11:59pm on Friday, October 31. 1 Introduction In this project, you will do the following: 1. Implement
More informationComputational Programming with Python
Numerical Analysis, Lund University, 2017 1 Computational Programming with Python Lecture 1: First steps - A bit of everything. Numerical Analysis, Lund University Lecturer: Claus Führer, Alexandros Sopasakis
More informationCOMP2611: Computer Organization. Data Representation
COMP2611: Computer Organization Comp2611 Fall 2015 2 1. Binary numbers and 2 s Complement Numbers 3 Bits: are the basis for binary number representation in digital computers What you will learn here: How
More informationVariable and Data Type I
Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store
More informationUser-Defined Function
ENGR 102-213 (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
More informationChapter 7. Expressions and Assignment Statements ISBN
Chapter 7 Expressions and Assignment Statements ISBN 0-321-49362-1 Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit
More informationPROGRAMMING IN HASKELL. Chapter 2 - First Steps
PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited
More informationChapter 7. Expressions and Assignment Statements
Chapter 7 Expressions and Assignment Statements Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment
More informationCOMPSCI 105 S Principles of Computer Science. Classes 3
S2 2017 Principles of Computer Science Classes 3 Exercise } Exercise } Create a Student class: } The Student class should have three attributes: id, last_name, and first_name. } Create a constructor to
More information1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.
1 class Lecture2 { 2 3 "Elementray Programming" 4 5 } 6 7 / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch. 2 in HS 11 / Zheng-Liang Lu Java Programming 41 / 68 Example Given the radius
More informationRoot Finding Methods. sympy and Sage. MCS 507 Lecture 13 Mathematical, Statistical and Scientific Software Jan Verschelde, 21 September 2011
wrap Root Finding Methods 1 2 wrap MCS 507 Lecture 13 Mathematical, Statistical and Scientific Software Jan Verschelde, 21 September 2011 Root Finding Methods 1 wrap 2 wrap wrap octave-3.4.0:1> p = [1,0,2,-1]
More informationComputer Programming CS F111
Computer Programming CS F111 BITS Pilani Dubai Campus NAND KUMAR Basics of C Programming BITS Pilani Dubai Campus Write a program that 1. Asks 5 marks from the user, find the average of the marks and print
More informationWeek 8: Operator overloading
Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading
More informationENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I
ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, 2 0 1 0 R E Z A S H A H I D I Today s class Constants Assignment statement Parameters and calling functions Expressions Mixed precision
More informationPython Scripting for Computational Science
Hans Petter Langtangen Python Scripting for Computational Science Third Edition With 62 Figures Sprin ger Table of Contents 1 Introduction 1 1.1 Scripting versus Traditional Programming 1 1.1.1 Why Scripting
More information6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1
6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.01 Introduction to EECS I Spring
More informationIt is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis
Chapter 14 Functional Programming Programming Languages 2nd edition Tucker and Noonan It is better to have 100 functions operate one one data structure, than 10 functions on 10 data structures. A. Perlis
More informationHigh Level Parallel Processing
High Level Parallel Processing 1 GPU computing with Maple enabling CUDA in Maple 15 stochastic processes and Markov chains 2 Multiprocessing in Python scripting in computational science the multiprocessing
More informationProgramming in C++ 5. Integral data types
Programming in C++ 5. Integral data types! Introduction! Type int! Integer multiplication & division! Increment & decrement operators! Associativity & precedence of operators! Some common operators! Long
More informationUser Interfaces. getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy
User Interfaces 1 Command Line Interfaces getting arguments of the command line a command line interface to store points fitting points with polyfit of numpy 2 Encapsulation by Object Oriented Programming
More informationIntroduction to Python. Didzis Gosko
Introduction to Python Didzis Gosko Scripting language From Wikipedia: A scripting language or script language is a programming language that supports scripts, programs written for a special run-time environment
More informationJim Lambers ENERGY 211 / CME 211 Autumn Quarter Programming Project 2
Jim Lambers ENERGY 211 / CME 211 Autumn Quarter 2007-08 Programming Project 2 This project is due at 11:59pm on Friday, October 17. 1 Introduction In this project, you will implement functions in order
More informationVariable and Data Type I
The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved
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 I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationPython Scripting for Computational Science
Hans Petter Langtangen Python Scripting for Computational Science Third Edition With 62 Figures 43 Springer Table of Contents 1 Introduction... 1 1.1 Scripting versus Traditional Programming... 1 1.1.1
More informationCS 234 Python Review Part 2
CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More information61A Lecture 6. Friday, September 7
61A Lecture 6 Friday, September 7 Lambda Expressions >>> ten = 10 An expression: this one evaluates to a number >>> square = x * x Also an expression: evaluates to a function >>> square = lambda x: x *
More informationCOSE212: Programming Languages. Lecture 3 Functional Programming in OCaml
COSE212: Programming Languages Lecture 3 Functional Programming in OCaml Hakjoo Oh 2017 Fall Hakjoo Oh COSE212 2017 Fall, Lecture 3 September 18, 2017 1 / 44 Why learn ML? Learning ML is a good way of
More informationPrefix/Infix/Postfix Notation
Prefix/Infix/Postfix Notation One commonly writes arithmetic expressions, such as 3 + 4 * (5-2) in infix notation which means that the operator is placed in between the two operands. In this example, the
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationAll the operations used in the expression are over integers. a takes a pair as argument. (a pair is also a tuple, or more specifically, a 2-tuple)
Weekly exercises in INF3110 week 41 6-10.10.2008 Exercise 1 Exercise 6.1 in Mitchell's book a) fun a(x,y) = x+2*y; val a = fn : int * int -> int All the operations used in the expression are over integers.
More informationRoundoff Errors and Computer Arithmetic
Jim Lambers Math 105A Summer Session I 2003-04 Lecture 2 Notes These notes correspond to Section 1.2 in the text. Roundoff Errors and Computer Arithmetic In computing the solution to any mathematical problem,
More informationParsing Scheme (+ (* 2 3) 1) * 1
Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes
More informationIMPORTANT QUESTIONS IN C FOR THE INTERVIEW
IMPORTANT QUESTIONS IN C FOR THE INTERVIEW 1. What is a header file? Header file is a simple text file which contains prototypes of all in-built functions, predefined variables and symbolic constants.
More informationFloating Point Puzzles. Lecture 3B Floating Point. IEEE Floating Point. Fractional Binary Numbers. Topics. IEEE Standard 754
Floating Point Puzzles Topics Lecture 3B Floating Point IEEE Floating Point Standard Rounding Floating Point Operations Mathematical properties For each of the following C expressions, either: Argue that
More informationPython Programming, bridging course 2011
Python Programming, bridging course 2011 About the course Few lectures Focus on programming practice Slides on the homepage No course book. Using online resources instead. Online Python resources http://www.python.org/
More informationCOSC 243. Data Representation 3. Lecture 3 - Data Representation 3 1. COSC 243 (Computer Architecture)
COSC 243 Data Representation 3 Lecture 3 - Data Representation 3 1 Data Representation Test Material Lectures 1, 2, and 3 Tutorials 1b, 2a, and 2b During Tutorial a Next Week 12 th and 13 th March If you
More informationUniversitetet i Oslo Institutt for informatikk. Scripting in High-Performance Computing. Roger Hansen. Cand Scient Thesis
Universitetet i Oslo Institutt for informatikk Scripting in High-Performance Computing Roger Hansen Cand Scient Thesis August, 2001 Abstract This thesis describes how the use of more than one type of
More informationChapter 7. Expressions and Assignment Statements (updated edition 11) ISBN
Chapter 7 Expressions and Assignment Statements (updated edition 11) ISBN 0-321-49362-1 Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean
More informationChapter 1. Fundamentals of Higher Order Programming
Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme
More informationCIS 110: Introduction to Computer Programming
CIS 110: Introduction to Computer Programming Lecture 3 Express Yourself ( 2.1) 9/16/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline 1. Data representation and types 2. Expressions 9/16/2011
More informationFixed-Point Math and Other Optimizations
Fixed-Point Math and Other Optimizations Embedded Systems 8-1 Fixed Point Math Why and How Floating point is too slow and integers truncate the data Floating point subroutines: slower than native, overhead
More information1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19
1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object
More informationReview Questions 26 CHAPTER 1. SCIENTIFIC COMPUTING
26 CHAPTER 1. SCIENTIFIC COMPUTING amples. The IEEE floating-point standard can be found in [131]. A useful tutorial on floating-point arithmetic and the IEEE standard is [97]. Although it is no substitute
More informationComputational Mathematics with Python
Numerical Analysis, Lund University, 2015 1 Computational Mathematics with Python Unit 7: Object oriented programming with classes Numerical Analysis, Lund University Lecturer: Claus Führer 2015 Classes
More informationENGR 101 Engineering Design Workshop
ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as
More information61A Lecture 26. Monday, October 31
61A Lecture 26 Monday, October 31 Programming Languages Computers have software written in many different languages Machine languages: statements can be interpreted by hardware All data are represented
More informationENGI Introduction to Computer Programming M A Y 2 8, R E Z A S H A H I D I
ENGI 1020 - Introduction to Computer Programming M A Y 2 8, 2 0 1 0 R E Z A S H A H I D I Last class Last class we talked about the following topics: Constants Assignment statements Parameters and calling
More informationComputer Architecture, Lecture 14: Does your computer know how to add?
Computer Architecture, Lecture 14: Does your computer know how to add? Hossam A. H. Fahmy Cairo University Electronics and Communications Engineering 1 / 25 A strange behavior What do you expect from this
More informationCS429: Computer Organization and Architecture
CS429: Computer Organization and Architecture Dr. Bill Young Department of Computer Sciences University of Texas at Austin Last updated: September 18, 2017 at 12:48 CS429 Slideset 4: 1 Topics of this Slideset
More information9/10/10. Arithmetic Operators. Today. Assigning floats to ints. Arithmetic Operators & Expressions. What do you think is the output?
Arithmetic Operators Section 2.15 & 3.2 p 60-63, 81-89 1 Today Arithmetic Operators & Expressions o Computation o Precedence o Associativity o Algebra vs C++ o Exponents 2 Assigning floats to ints int
More informationReview: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements
Review: Exam 1 9/20/06 CS150 Introduction to Computer Science 1 1 Your First C++ Program 1 //*********************************************************** 2 // File name: hello.cpp 3 // Author: Shereen Khoja
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationFall Lecture 3 September 4. Stephen Brookes
15-150 Fall 2018 Lecture 3 September 4 Stephen Brookes Today A brief remark about equality types Using patterns Specifying what a function does equality in ML e1 = e2 Only for expressions whose type is
More informationLecture Numbers. Richard E Sarkis CSC 161: The Art of Programming
Lecture Numbers Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To understand the concept of data types To be familiar with the basic numeric data types in Python To be able
More informationLesson #3. Variables, Operators, and Expressions. 3. Variables, Operators and Expressions - Copyright Denis Hamelin - Ryerson University
Lesson #3 Variables, Operators, and Expressions Variables We already know the three main types of variables in C: int, char, and double. There is also the float type which is similar to double with only
More informationWeb Clients and Crawlers
Web Clients and Crawlers 1 Web Clients alternatives to web browsers opening a web page and copying its content 2 Scanning Files looking for strings between double quotes parsing URLs for the server location
More informationCSCI-GA Scripting Languages
CSCI-GA.3033.003 Scripting Languages 12/02/2013 OCaml 1 Acknowledgement The material on these slides is based on notes provided by Dexter Kozen. 2 About OCaml A functional programming language All computation
More informationExpressions and Assignment Statements
Expressions and Assignment Statements Introduction Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation, need to be familiar with
More informationExpressions and Assignment
Expressions and Assignment COS 301: Programming Languages Outline Other assignment mechanisms Introduction Expressions: fundamental means of specifying computations Imperative languages: usually RHS of
More informationNumerical Methods in Physics. Lecture 1 Intro & IEEE Variable Types and Arithmetic
Variable types Numerical Methods in Physics Lecture 1 Intro & IEEE Variable Types and Arithmetic Pat Scott Department of Physics, Imperial College November 1, 2016 Slides available from http://astro.ic.ac.uk/pscott/
More informationTo figure this out we need a more precise understanding of how ML works
Announcements: What are the following numbers: 74/2/70/17 (2:30,2:30,3:35,7:30) PS2 due Thursday 9/20 11:59PM Guest lecture on Tuesday 9/25 o No RDZ office hours next Friday, I am on travel A brief comment
More informationChapter 2 Working with Data Types and Operators
JavaScript, Fourth Edition 2-1 Chapter 2 Working with Data Types and Operators At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics
More informationChapter 2: Using Data
Chapter 2: Using Data TRUE/FALSE 1. A variable can hold more than one value at a time. F PTS: 1 REF: 52 2. The legal integer values are -2 31 through 2 31-1. These are the highest and lowest values that
More informationTable of Contents EVALUATION COPY
Table of Contents Introduction... 1-2 A Brief History of Python... 1-3 Python Versions... 1-4 Installing Python... 1-5 Environment Variables... 1-6 Executing Python from the Command Line... 1-7 IDLE...
More informationFloating Point January 24, 2008
15-213 The course that gives CMU its Zip! Floating Point January 24, 2008 Topics IEEE Floating Point Standard Rounding Floating Point Operations Mathematical properties class04.ppt 15-213, S 08 Floating
More information8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );
- 50 - Control Structures: 8. Functions (II) Arguments passed by value and by reference. Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value. This
More informationIntroduction to Programming, Aug-Dec 2006
Introduction to Programming, Aug-Dec 2006 Lecture 3, Friday 11 Aug 2006 Lists... We can implicitly decompose a list into its head and tail by providing a pattern with two variables to denote the two components
More informationIntroduction to Programming
Introduction to Programming Department of Computer Science and Information Systems Tingting Han (afternoon), Steve Maybank (evening) tingting@dcs.bbk.ac.uk sjmaybank@dcs.bbk.ac.uk Autumn 2017 Week 4: More
More information