Chapter 24 Numerics Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 17 vector and Free Store Bjarne Stroustrup
Advertisements

Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 19 Vectors, templates, and exceptions Bjarne Stroustrup
Chapter 24 Numerics Bjarne Stroustrup
Chapter 18 Vectors and Arrays
Chapter 18 Vectors and Arrays John Keyser’s Modification of Slides by Bjarne Stroustrup
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Chapter 17 vector and Free Store John Keyser’s Modifications of Slides By Bjarne Stroustrup
Transformations We want to be able to make changes to the image larger/smaller rotate move This can be efficiently achieved through mathematical operations.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Lecture 4 Sept 4 Goals: chapter 1 (completion) 1-d array examples Selection sorting Insertion sorting Max subsequence sum Algorithm analysis (Chapter 2)
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
College Algebra Fifth Edition James Stewart Lothar Redlin Saleem Watson.
Mathematical Fundamentals
Chapter 10 Review: Matrix Algebra
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
Matlab tutorial course Lesson 2: Arrays and data types
Lecture 11 vector and Free Store Bjarne Stroustrup
Multi-Dimensional Arrays
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 17 vector and Free Store Hartmut Kaiser
Array Addition  Two arrays can be added if and only if both arrays have exactly the same dimensions.  Assuming the dimension requirement is satisfied,
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
C++ Tutorial Hany Samuel and Douglas Wilhelm Harder Department of Electrical and Computer Engineering University of Waterloo Copyright © 2006 by Douglas.
Summary of what we learned yesterday Basics of C++ Format of a program Syntax of literals, keywords, symbols, variables Simple data types and arithmetic.
Pointers OVERVIEW.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Working with Batches of Data Lecture 4 Hartmut Kaiser
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
CS 11 C++ track: lecture 3 Today const and const -correctness operator overloading.
POINTERS.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 17: Vectors and Arrays 1 Based on slides created by Bjarne Stroustrup.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Computer Graphics Basic Maths for Graphics in C++ CO2409 Computer Graphics Week 4.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Simple Data Types Chapter Constants Revisited t Three reasons to use constants –Constant is recognizable –Compiler prevents changes in value.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
EGR 115 Introduction to Computing for Engineers MATLAB Basics 1: Variables & Arrays Wednesday 03 Sept 2014 EGR 115 Introduction to Computing for Engineers.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
1 ENERGY 211 / CME 211 Lecture 4 September 29, 2008.
Arrays. C++ Style Data Structures: Arrays(1) An ordered set (sequence) with a fixed number of elements, all of the same type, where the basic operation.
Computer Graphics Mathematical Fundamentals Lecture 10 Taqdees A. Siddiqi
Introduction to Programming Lecture # 43. Math Library Complex number Matrix Quadratic equation and their solution …………….…
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Chapter 18 Vectors and Arrays Bjarne Stroustrup
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Computer Graphics Basic Maths for Graphics in C++
Chapter 18 Vectors and Arrays
Bjarne Stroustrup Chapter 24 Numerics Bjarne Stroustrup
Lecture: MATLAB Chapter 1 Introduction
Chapter 18 Vectors and Arrays
Built-In (a.k.a. Native) Types in C++
Chapter 17 vector and Free Store
Managing 2D Arrays Simple Dynamic Allocation
Math review - scalars, vectors, and matrices
Presentation transcript:

Chapter 24 Numerics Bjarne Stroustrup

Abstract This lecture is an overview of the fundamental tools and techniques for numeric computation. For some, numerics are everything. For many, numerics are occasionally essential. Here, we present the basic problems of size, precision, truncation, and error handling in standard mathematical functions. We present multidimensional matrices and the standard library complex numbers. This lecture is an overview of the fundamental tools and techniques for numeric computation. For some, numerics are everything. For many, numerics are occasionally essential. Here, we present the basic problems of size, precision, truncation, and error handling in standard mathematical functions. We present multidimensional matrices and the standard library complex numbers. 2Stroustrup/PPP - Nov'13

Overview Precision, overflow, sizes, errors Precision, overflow, sizes, errors Matrices Matrices Random numbers Random numbers Complex numbers Complex numbers Please note: Please note: Again, we are exploring how to express the fundamental notions of an application domain in code Again, we are exploring how to express the fundamental notions of an application domain in code Numerical computation, especially linear algebra Numerical computation, especially linear algebra We are showing the basic tools only. The computational techniques for using these tools well, say in engineering calculations, you’ll have to learn elsewhere We are showing the basic tools only. The computational techniques for using these tools well, say in engineering calculations, you’ll have to learn elsewhere That’s “domain knowledge” beyond the scope of this presentation That’s “domain knowledge” beyond the scope of this presentation 3Stroustrup/PPP - Nov'13

Precision, etc. When we use the built-in types and usual computational techniques, numbers are stored in fixed amounts of memory When we use the built-in types and usual computational techniques, numbers are stored in fixed amounts of memory Floating-point numbers are (only) approximations of real numbers Floating-point numbers are (only) approximations of real numbers float x = 1.0/333; float sum = 0; for (int i=0; i<333; ++i) sum+=x; cout << sum << "\n";// Integer types represent (relatively) small integers only Integer types represent (relatively) small integers only short y = 40000; int i = ; cout << y << " " << i*i << "\n";// There just aren’t enough bits to exactly represent every number we need in a way that’s amenable to efficient computation There just aren’t enough bits to exactly represent every number we need in a way that’s amenable to efficient computation 4Stroustrup/PPP - Nov'13

Sizes The exact sizes of C++ built-in types depends on the hardware and the compiler The exact sizes of C++ built-in types depends on the hardware and the compiler These sizes are for Windows using Microsoft, GCC on Linux, and others These sizes are for Windows using Microsoft, GCC on Linux, and others sizeof(x) gives you the size of x in bytes sizeof(x) gives you the size of x in bytes By definition, sizeof(char)==1 By definition, sizeof(char)==1 Unless you have a very good reason for something else, stick to bool, char, int, and double Unless you have a very good reason for something else, stick to bool, char, int, and double 5 char int short double floatlongint* Stroustrup/PPP - Nov'13

Sizes, overflow, truncation // when you calculate, you must be aware of possible overflow and truncation // Beware: C++ will not catch such problems for you void f(char c, short s, int i, long lg, float fps, double fpd) { c = i;// yes: chars really are very small integers (not a good idea) s = i; i = i+1;// what if i was the largest int? lg = i*i;// beware: a long may not be any larger than an int // and anyway, i*i is an int – possibly it already overflowed fps = fpd; i = fpd;// truncates: e.g > 5 fps = i;// you can lose precision (for very large int values) char ch = 0;// try this for (int i = 0; i<500; ++i) { cout << int(ch) << "\t"; ++ch; }} 6Stroustrup/PPP - Nov'13

If in doubt, you can check The simplest way to test The simplest way to test Assign, then compare Assign, then compare void f(int i) { char c = i;// may throw away information you don’t want to loose if (c != i) { // oops! We lost information, figure out what to do } // … } That’s what narrow_cast from std_lib_facilities.h does That’s what narrow_cast from std_lib_facilities.h does 7Stroustrup/PPP - Nov'13

Math function errors If a standard mathematical function can’t do its job, it sets errno from, for example If a standard mathematical function can’t do its job, it sets errno from, for example void f(double negative, double very_large) // primitive (1974 vintage, pre-C++) but ISO standard error handling { errno = 0;// no current errors sqrt(negative);// not a good idea if (errno){ /* … */ }// errno!=0 means ‘something went wrong” if (errno == EDOM)// domain error cerr << "sqrt() not defined for negative argument\n"; cerr << "sqrt() not defined for negative argument\n"; pow(very_large,2);// not a good idea (and did you spot the bug?) if (errno==ERANGE)// range error cerr << "pow(" << very_large << ",2) too large for a double\n"; cerr << "pow(" << very_large << ",2) too large for a double\n";} 8Stroustrup/PPP - Nov'13

Matrices The standard vector and the built-in array are one dimensional The standard vector and the built-in array are one dimensional What if we need 2 dimensions? (e.g. a matrix) What if we need 2 dimensions? (e.g. a matrix) N dimensions? N dimensions? 9 A vector (e.g. Matrix v(4) ), also called a 1-dimensional Matrix, or even a 1*N matrix A 3*4 matrix (e.g. Matrix m(3,4) ), also called a 2-dimensional Matrix Stroustrup/PPP - Nov'13

Matrices Matrix m(3,4); Matrix m(3,4); 10 A 3*4 matrix, also called a 2-dimensional Matrix 3 rows 4 columns A row A column Stroustrup/PPP - Nov'13

C-style multidimensional Arrays A built-in facility A built-in facility int ai[4];// 1-dimensional array double ad[3][4];// 2-dimensional array char ac[3][4][5];// 3-dimensional array ai[1] =7; ad[2][3] = 7.2; ac[2][3][4] = 'c'; Basically, Arrays of Arrays Basically, Arrays of Arrays 11Stroustrup/PPP - Nov'13

C-style multidimensional Arrays Problems Problems C-style multidimensional Arrays are Arrays of Arrays C-style multidimensional Arrays are Arrays of Arrays Fixed sizes (i.e. fixed at compile time) Fixed sizes (i.e. fixed at compile time) If you want to determine a size at run-time, you’ll have to use free store If you want to determine a size at run-time, you’ll have to use free store Can’t be passed cleanly Can’t be passed cleanly An Array turns into a pointer at the slightest provocation An Array turns into a pointer at the slightest provocation No range checking No range checking As usual, an Array doesn’t know its own size As usual, an Array doesn’t know its own size No Array operations No Array operations Not even assignment (copy) Not even assignment (copy) A major source of bugs A major source of bugs And, for most people, they are a serious pain to write And, for most people, they are a serious pain to write Look them up only if you are forced to use them Look them up only if you are forced to use them E.g. TC++PL4, pp E.g. TC++PL4, pp Stroustrup/PPP - Nov'13

C-style multidimensional Arrays You can’t pass multidimensional Arrays cleanly You can’t pass multidimensional Arrays cleanly void f1(int a[3][5]);// useful for [3][5] matrices only Can’t read vector with size from input and then call f1 Can’t read vector with size from input and then call f1 (unless the size happens to be 3*5) (unless the size happens to be 3*5) Can’t write a recursive/adaptive function Can’t write a recursive/adaptive function void f2(int [ ][5], int dim1);// 1 st dimension can be a variable void f3(int[ ][ ], int dim1, int dim2); // error (and wouldn’t work anyway) void f4(int* m, int dim1, int dim2)// odd, but works { for (int i=0; i<dim1; ++i) for (int j = 0; j<dim2; ++j) for (int j = 0; j<dim2; ++j) m[i*dim2+j] = 0; } 13Stroustrup/PPP - Nov'13

A Matrix library // on the textbook website: Matrix.h #include "Matrix.h" void f(int n1, int n2, int n3) { Matrix ad1(n1);// default: one dimension Matrix ai1(n1); Matrix ad2(n1,n2);// 2-dimensional Matrix ad3(n1,n2,n3);// 3-dimensional ad1(7) = 0;// subscript using ( ) – Fortran style ad1[7] = 8;// [ ] also works – C style ad2(3,4) = 7.5;// true multidimensional subscripting ad3(3,4,5) = 9.2; } 14Stroustrup/PPP - Nov'13

A Matrix library “like your math/engineering textbook talks about Matrices” “like your math/engineering textbook talks about Matrices” Or about vectors, matrices, tensors Or about vectors, matrices, tensors Compile-time and run-time checked Compile-time and run-time checked Matrices of any dimension Matrices of any dimension 1, 2, and 3 dimensions actually work (you can add more if/as needed) 1, 2, and 3 dimensions actually work (you can add more if/as needed) Matrices are proper variables/objects Matrices are proper variables/objects You can pass them around You can pass them around Usual Matrix operations Usual Matrix operations Subscripting: ( ) Subscripting: ( ) Slicing: [ ] Slicing: [ ] Assignment: = Assignment: = Scaling operations (+=, -=, *=, %=, etc.) Scaling operations (+=, -=, *=, %=, etc.) Fused vector operations (e.g., res[i] = a[i]*c+b[i]) Fused vector operations (e.g., res[i] = a[i]*c+b[i]) Dot product (res = sum of a[i]*b[i]) Dot product (res = sum of a[i]*b[i]) Performs equivalently to hand-written low-level code Performs equivalently to hand-written low-level code You can extend it yourself as needed (“no magic”) You can extend it yourself as needed (“no magic”) 15Stroustrup/PPP - Nov'13

A Matrix library // compile-time and run-time error checking void f(int n1, int n2, int n3) { Matrix ad1(5);// default: one dimension Matrix ai(5); Matrix ad11(7); Matrix ad2(n1);// error: length of 2 nd dimension missing Matrix ad3(n1,n2,n3); Matrix ad33(n1,n2,n3); ad1(7) = 0;// Matrix_error exception; 7 is out of range ad1 = ai;// error: different element types ad1 = ad11;// Matrix_error exception; different dimensions ad2(3) = 7.5;// error: wrong number of subscripts ad3 = ad33;// ok: same element type, same dimensions, same lengths } 16Stroustrup/PPP - Nov'13

A Matrix library As the elements are laid out in memory ("row-wise"): As the elements are laid out in memory ("row-wise"): As we consider the matrix (row, column): a[0]: a[1]: a[2]: a[1][2] a(1,2) Matrix a(3,4); Stroustrup/PPP - Nov'13

A Matrix library void init(Matrix & a) // initialize each element to a characteristic value { for (int i=0; i<a.dim1(); ++i) for (int j = 0; j<a.dim2(); ++j) a(i,j) = 10*i+j; } void print(const Matrix & a) // print the elements of Matrix a, row by row { for (int i=0; i<a.dim1(); ++i) { for (int j = 0; j<a.dim2(); ++j) cout << a(i,j) << '\t'; cout << '\n'; }} 18Stroustrup/PPP - Nov'13

2D and 3D Matrices // 2D space (e.g. a game board): enum Piece { none, pawn, knight, queen, king, bishop, rook }; Matrix board(8,8);// a chessboard Piece init_pos[] = { rook, knight, bishop, queen, king, bishop, knight, rook }; // 3D space (e.g. a physics simulation using a Cartesian grid): int grid_nx;// grid resolution; set at startup int grid_ny; int grid_nz; Matrix cube(grid_nx, grid_ny, grid_nz); 19Stroustrup/PPP - Nov'13

1D Matrix Matrix a(10);// means Matrix a(10); a.size();// number of elements a.dim1();// number of elements int* p = a.data();// extract data as a pointer to a C-style array a(i);// i th element (Fortran style), but range checked a[i];// i th element (C-style), but range checked Matrix a2 = a;// copy initialization a = a2;// copy assignment a *= 7;// scaling a(i)*=7 for each i (also +=, -=, /=, etc.) a.apply(f);// a(i)=f(a(i)) for each element a(i) a.apply(f,7); // a(i)=f(a(i),7) for each element a(i) b =apply(f,a);// make a new Matrix with b(i)==f(a(i)) b =apply(f,a,7);// make a new Matrix with b(i)==f(a(i),7) Matrix a3 = scale_and_add(a,8,a2);// fused multiply and add int r = dot_product(a3,a);// dot product 20Stroustrup/PPP - Nov'13

2D Matrix (very like 1D) Matrix a(10,20); a.size();// number of elements a.dim1();// number of elements in a row a.dim2();// number of elements in a column int* p = a.data();// extract data as a pointer to a C-style array a(i,j);// (i,j) th element (Fortran style), but range checked a[i];// i th row (C-style), but range checked a[i][j];// (i,j) th element C-style Matrix a2 = a;// copy initialization a = a2;// copy assignment a *= 7;// scaling (and +=, -=, /=, etc.) a.apply(f);// a(i,j)=f(a(i,j)) for each element a(i,j) a.apply(f,7); // a(i,j)=f(a(i,j),7) for each element a(i,j) b=apply(f,a);// make a new Matrix with b(i,j)==f(a(i,j)) b=apply(f,a,7);// make a new Matrix with b(i,j)==f(a(i,j),7) a.swap_rows(7,9);// swap rows a[7]  a[9] 21Stroustrup/PPP - Nov'13

3D Matrix (very like 1D and 2D) Matrix a(10,20,30); a.size();// number of elements a.dim1();// number of elements in dimension 1 a.dim2();// number of elements in dimension 2 a.dim3();// number of elements in dimension 3 int* p = a.data();// extract data as a pointer to a C-style Matrix a(i,j,k);// (i,j,k) th element (Fortran style), but range checked a[i];// i th row (C-style), but range checked a[i][j][k];// (i,j,k) th element C-style Matrix a2 = a;// copy initialization a = a2;// copy assignment a *= 7;// scaling (and +=, -=, /=, etc.) a.apply(f);// a(i,j,k)=f(a(i,j)) for each element a(i,j,k) a.apply(f,7); // a(i,j,k)=f(a(i,j),7) for each element a(i,j,k) b=apply(f,a);// make a new Matrix with b(i,j,k)==f(a(i,j,k)) b=apply(f,a,7);// make a new Matrix with b(i,j,k)==f(a(i,j,k),7) a.swap_rows(7,9);// swap rows a[7]  a[9] 22Stroustrup/PPP - Nov'13

Using Matrix See book See book Matrix I/O Matrix I/O §24.5.4; it’s what you think it is §24.5.4; it’s what you think it is Solving linear equations example Solving linear equations example §24.6; it’s just like your algebra textbook says it is §24.6; it’s just like your algebra textbook says it is 23Stroustrup/PPP - Nov'13

Implementing Matrix A Matrix is a handle A Matrix is a handle Controlling access to a sequence of elements Controlling access to a sequence of elements Let’s examine a simplified and improved variant of the idea Let’s examine a simplified and improved variant of the idea That is, not exactly what’s provided as Matrix.h That is, not exactly what’s provided as Matrix.h template class Matrix { public: // interface, as described protected: T* elem;// elements stored as a linear sequence array extents;// number of elements in each dimension }; Stroustrup/PPP - Nov'1324 Matrix elements

Implementing Matrix Resource management: Resource management: A Matrix must manage the lifetimes of its elements A Matrix must manage the lifetimes of its elements Constructors allocate memory for elements and initialize elements Constructors allocate memory for elements and initialize elements The destructor destroys elements and deallocates memory for elements The destructor destroys elements and deallocates memory for elements Assignment copies elements Assignment copies elements Stroustrup/PPP - Nov'1325 Matrix elements

Implementing Matrix We need constructors: We need constructors: Constructor for default elements Constructor for default elements Matrix ::Matrix(Index,Index); Matrix ::Matrix(Index,Index); Matrix m0(2,3);// 2 by 3 matrix each element initialized to 0 Matrix m0(2,3);// 2 by 3 matrix each element initialized to 0 Initializer-list constructor (C++11) Initializer-list constructor (C++11) Matrix ::Matrix(std::initializer_list ); Matrix ::Matrix(std::initializer_list ); Matrix m1 = {{1,2,3},{4,5,6}}; // 2 by 3 matrix Matrix m1 = {{1,2,3},{4,5,6}}; // 2 by 3 matrix Copy constructor Copy constructor Matrix ::Matrix(const Matrix&); Matrix ::Matrix(const Matrix&); Matrix m2 = m1;// m2 is a copy of m1 Matrix m2 = m1;// m2 is a copy of m1 Move constructors (C++11) Move constructors (C++11) Matrix ::Matrix(Matrix&&); Matrix ::Matrix(Matrix&&); return m1;// move m1 to somewhere else return m1;// move m1 to somewhere else Stroustrup/PPP - Nov'1326 Matrix elements

How to move a Matrix Idea #1: Idea #1: Return a pointer to a new’d object Return a pointer to a new’d object Matrix* operator+(const Matrix&, const Matrix&); Matrix& res = *(a+b);// ugly! (unacceptable) Who does the delete? Who does the delete? there is no good general answer there is no good general answer Stroustrup/PPP - Nov'13 Matrix elements 27

How to move a Matrix Idea #2 Idea #2 Return a reference to a new’d object Return a reference to a new’d object Matrix& operator+(const Matrix&, const Matrix&); Matrix res = a+b;// looks right, but … Who does the delete? Who does the delete? What delete? I don’t see any pointers. What delete? I don’t see any pointers. there is no good general answer there is no good general answer Stroustrup/PPP - Nov'13 Matrix elements 28

How to move a Matrix Idea #3 Idea #3 Pass an reference to a result object Pass an reference to a result object void operator+(const Matrix&, const Matrix&, Matrix& result); Matrix res = a+b;// Oops, doesn’t work for operators Matrix res2; operator+(a,b,res2);// Ugly! We are regressing towards assembly code We are regressing towards assembly code Stroustrup/PPP - Nov'13 Matrix elements 29

How to move a resource Idea #4 Idea #4 Return a Matrix Return a Matrix Matrix operator+(const Matrix&, const Matrix&); Matrix res = a+b; Copy? Copy? expensive expensive Use some pre-allocated “result stack” of Matrixes Use some pre-allocated “result stack” of Matrixes A brittle hack A brittle hack Move the Matrix out Move the Matrix out don’t copy; “steal the representation” don’t copy; “steal the representation” Directly supported in C++11 through move constructors Directly supported in C++11 through move constructors Stroustrup/PPP - Nov'13 Matrix elements 30

Move semantics Return a Matrix Return a Matrix Matrix operator+(const Matrix& a, const Matrix& b) { Matrix r; // copy a[i]+b[i] into r[i] for each i return r; } Matrix res = a+b; Define move a constructor for Matrix Define move a constructor for Matrix don’t copy; “steal the representation” don’t copy; “steal the representation” …….. res: r: Stroustrup/PPP - Nov'1331

Move semantics Direct support in C++11: Move constructor Direct support in C++11: Move constructor class Matrix { // … Matrix(Matrix&& a)// move constructor { elem = a.elem;// *this gets a’s elements a.elem = nullptr;// a becomes the empty Matrix extents = a.extents;// copy extents }}; Matrix res = a+b; …….. res: r: Stroustrup/PPP - Nov'1332

Random numbers A “random number” is a number from a sequence that matches a distribution, but where it is hard to predict the next number in the sequence A “random number” is a number from a sequence that matches a distribution, but where it is hard to predict the next number in the sequence Avoid C-style random numbers from Avoid C-style random numbers from Use (C++11) Use (C++11) class Rand_int { public: Rand_int(int low, int high) :dist{low,high} { } int operator()() { return dist(re); }// draw an int private: default_random_engine re;// generates random numbers uniform_int_distribution<> dist;// makes the distribution uniform }; 33Stroustrup/PPP - Nov'13

Random numbers Make a histogram Make a histogram int main() { constexpr int max = 9; Rand_int rnd {0,max};// make a uniform random number generator vector histogram(max+1) ;// make a vector of appropriate size for (int i=0; i!=200; ++i) // fill the histogram ++histogram[rnd()]; for (int i = 0; i!=histogram.size(); ++i) {// write out a bar graph cout << i << '\t'; for (int j=0; j!=histogram[i]; ++j) cout << '*'; cout << endl; }} 34Stroustrup/PPP - Nov'13

Random numbers We get We get 0********************* 1**************** 2******************* 3******************** 4**************** 5*********************** 6************************** 7*********** 8********************** 9************************* 35Stroustrup/PPP - Nov'13

Complex Standard library complex types from Standard library complex types from template class complex { T re, im; // a complex is a pair of scalar values, a coordinate pair public: complex(const T& r, const T& i) :re(r), im(i) { } complex(const T& r) :re(r),im(T()) { } complex() :re(T()), im(T()) { } // or combine: complex(const T& r=T(), const T& i=T()) :re(r), im(i) { } T real() { return re; } T imag() { return im; } // operators: = += -= *= /= }; // operators: + - / * == != // whatever standard mathematical functions that apply to complex: // pow(), abs(), sqrt(), cos(), log(), etc. and also norm() (square of abs()) 36Stroustrup/PPP - Nov'13

Complex // use complex exactly like a built-in type, such as double // just remember that not all operations are defined for a complex (e.g. <) typedef complex dcmplx; // sometimes complex gets verbose void f( dcmplx z, vector >& vc) // C++11 allows vector > with no space between > > {; dcmplx z2 = pow(z,2); dcmplx z3 = z2*9+vc[3]; dcmplx sum = accumulate(vc.begin(), vc.end(), dcmplx()); } 37Stroustrup/PPP - Nov'13

Numeric limits Each C++ implementation specifies properties of the built-in types Each C++ implementation specifies properties of the built-in types used to check against limits, set sentinels, etc. used to check against limits, set sentinels, etc. From From for each type for each type min()// smallest value, e.g., numeric_limits ::min() min()// smallest value, e.g., numeric_limits ::min() max()// largest value max()// largest value … For floating-point types For floating-point types Lots (look it up if you ever need it) Lots (look it up if you ever need it) E.g. numeric_limits ::max_exponent10 E.g. numeric_limits ::max_exponent10 From and From and INT_MAX// largest int value INT_MAX// largest int value DBL_MIN// smallest positive double value DBL_MIN// smallest positive double value 38Stroustrup/PPP - Nov'13

Numeric limits They are important to low-level tool builders They are important to low-level tool builders If you think you need them, you are probably too close to hardware, but there are a few other uses. For example, If you think you need them, you are probably too close to hardware, but there are a few other uses. For example, void f(const vector & vc) { // pedestrian (and has a bug): int smallest1 = v[0]; for (int i = 1; i < vc.size(); ++i) if (v[i] < smallest1) smallest1 = v[i]; // better: int smallest2 = numeric_limits ::max(); for (int i = 0; i < vc.size(); ++i) if (v[i] < smallest2) smallest2 = v[i]; // or use standard library: vector ::iterator p = min_element(vc.begin(),vc.end()); // and check for p==vc.end() } 39Stroustrup/PPP - Nov'13

C++11 Compilers (all free) Compilers (all free) GCC GCC Clang Clang VC++ VC++ … Books Books TC++PL4 (complete) TC++PL4 (complete) Tour++ (short overview) Tour++ (short overview) … Websites Websites … Videos Videos … Stroustrup/PPP - Nov'1340

A great link A great link for anyone who likes math A great link for anyone who likes math Or simply needs to use math Or simply needs to use math Famous mathematicians Famous mathematicians Biography, accomplishments, plus curios, for example, who is the only major mathematician to win an Olympic medal? Biography, accomplishments, plus curios, for example, who is the only major mathematician to win an Olympic medal? Famous curves Famous curves Famous problems Famous problems Mathematical topics Mathematical topics Algebra Algebra Analysis Analysis Numbers and number theory Numbers and number theory Geometry and topology Geometry and topology Mathematical physics Mathematical physics Mathematical astronomy Mathematical astronomy The history of mathematics The history of mathematics … 41Stroustrup/PPP - Nov'13