Lecture 14 Xiaoguang Wang STAT 598W March 11th, 2014 (STAT 598W) Lecture 14 1 / 36
Outline 1 Some other terms: Namespace and Input/Output 2 Armadillo C++ 3 Application (STAT 598W) Lecture 14 2 / 36
Outline 1 Some other terms: Namespace and Input/Output 2 Armadillo C++ 3 Application (STAT 598W) Lecture 14 3 / 36
Namespace Namespaces allow to group entities like classes, objects and functions under a name. Format: namespace identifier { entities identifier: any valid identifier; entities: the set of classes, objects and functions that are included within the namespace. (STAT 598W) Lecture 14 4 / 36
Namespaces Example: namespace mynamespace { int a, b; To access the previous variables from outside mynamespace we can write: mynamespace::a mynamespace::b (STAT 598W) Lecture 14 5 / 36
Namespaces: Example The functionality of namespaces is especially useful in the case that there is a possibility that a global object or function uses the same identifier as another one, causing redefinition errors. Example: // namespaces #include <iostream> using namespace std; namespace first { int var = 5; (STAT 598W) Lecture 14 6 / 36
Namespaces: Example (Continued) namespace second { double var = 3.1416; int main () { cout << first::var << endl; cout << second::var << endl; return 0; (STAT 598W) Lecture 14 7 / 36
Key Word Using: Example 1 The keyword using is used to introduce a name from a namespace into the current declarative region. Example: // using #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; (STAT 598W) Lecture 14 8 / 36
Key Word Using: Example 1 (Continued) namespace second { double x = 3.1416; double y = 2.7183; int main () { using first::x; using second::y; cout << x << endl; cout << y << endl; cout << first::y << endl; cout << second::x << endl; return 0; (STAT 598W) Lecture 14 9 / 36
Key Word Using: Example 2 The keyword using can also be used as a directive to introduce an entire namespace. Example: // using #include <iostream> using namespace std; namespace first { int x = 5; int y = 10; (STAT 598W) Lecture 14 10 / 36
Key Word Using: Example 2 (Continued) namespace second { double x = 3.1416; double y = 2.7183; int main () { using namespace first; cout << x << endl; cout << y << endl; cout << second::x << endl; cout << second::y << endl; return 0; (STAT 598W) Lecture 14 11 / 36
Key Word Using: Example 3 using and using namespace have validity only in the same block in which they are stated or in the entire code if they are used directly in the global scope. Example: // using namespace example #include <iostream> using namespace std; namespace first { int x = 5; (STAT 598W) Lecture 14 12 / 36
Key Word Using: Example 3 (Continued) namespace second { double x = 3.1416; int main () { { using namespace first; cout << x << endl; { using namespace second; cout << x << endl; return 0; (STAT 598W) Lecture 14 13 / 36
Namespaces Namespace alias: We can declare alternate names for existing namespaces according to the following format: namespace new_name = current_name; Namespace std: All the files in the C++ standard library declare all of its entities within the std namespace. That is why we have generally included the using namespace std. (STAT 598W) Lecture 14 14 / 36
File Input and Output The fstream header includes the following classes: ofstream : Stream class to write on files ifstream : Stream class to read from files fstream : Stream class to both read from and write on files Once an object of one of the above classes types is declared and associated with a file, it can be used with the insertion operator or the extraction operator in much the same way as cout or cin. (STAT 598W) Lecture 14 15 / 36
Example: Basic file operations #include<fstream> using namespace std; int main(){ ofstream myfile; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close(); return 0; (STAT 598W) Lecture 14 16 / 36
Opening the file The line: myfile.open ("example.txt"); opens a file called example.txt and assigns to it the output stream object myfile. The open function can take a second argument, the mode, which helps determine its behaviour. Each stream class has the mode set by default if no second argument is given. Warning: When I ran it, the ofstream overwrote the file each time. If we had just wanted to append text to the end of the file, we would need to specify the mode when we open the file as myfile.open ("example.txt", ios::app); If the program fails to open the file, it may not explicitly give an error. We can check whether it was successful by using myfile.is_open() which will return true if and only if myfile currently corresponds to an open file. (STAT 598W) Lecture 14 17 / 36
Data input and output Additionally, fstream objects also come with several boolean functions to help control data flow and detect errors. bad() : Returns true if read/write operation fails. fail() : Returns true if read/write operation fails, or if a formatting error occurs. eof() : Returns true if read operation has reached the end of the file. good() : Returns false if any of the above is true. Once finished, you should always close the file with the close() function. In the case of an output stream, text isnt written to the file immediately when you write to the stream, but rather is stored in a buffer. The call to close() signals the program to finish writing to the file. (STAT 598W) Lecture 14 18 / 36
Another Example for reading data #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string line; ifstream myfile ("example.txt"); if (myfile.is_open()) { while ( getline (myfile,line) ) { cout << line << \n ; myfile.close(); else cout << "Unable to open file"; return 0; (STAT 598W) Lecture 14 19 / 36
Outline 1 Some other terms: Namespace and Input/Output 2 Armadillo C++ 3 Application (STAT 598W) Lecture 14 20 / 36
Introduction Developed by the National Information and Commmunications Technology of Australia (NICTA) and from contributions around the world. (Conrad Sanderson) GNU Software. C++ linear algebra library that outperforms NEWMAT and IT++ in speed and ease of use. Armadillo aims to replicate most of the MATLAB s operations within C++. (STAT 598W) Lecture 14 21 / 36
C-make installation We need to install cmake first: http://www.cmake.org/cmake/resources/software.html. Download cmake-2.8.10.2.tar.gz in your home directory. Extract the installation files: tar xzf cmake-2.8.10.2.tar.gz Create a new folder in your home directory (say ~/opt) in order to contain library and header files. Go to the installation folder and type:./bootstrap --prefix=~/opt make make install (STAT 598W) Lecture 14 22 / 36
Installation Download the most current version of Armadillo (http://arma.sourceforge.net/download.html) in your home directory. Follow the installation procedures in the same webpage (depending on your operating system). In class we will perform the most basic installation of Linux (without using LAPACK and BLAS libraries). Untar the installation file: tar xzf armadillo-3.800.0.tar.gz Go to the installation folder and type: ~/opt/bin/cmake. make make install DESTDIR=~/opt (STAT 598W) Lecture 14 23 / 36
Example 1 #include <iostream> #include "armadillo" using namespace std; using namespace arma; int main() { mat A = randu<mat>(4,5); mat B = randu<mat>(4,5); cout << A*trans(B) << endl; return 0; Run it as (assume the code file named as name.cpp and the output named as name ): g++ -Wall -g -I ~/opt/usr/include name.cpp -o name -O2 (STAT 598W) Lecture 14 24 / 36
Matrix class See http://arma.sourceforge.net/docs.html for more details. mat type: matrix containing double or integer numbers. It admits several constructors: mat(), mat(n_rows,n_cols), etc. Matrix attributes:.n_rows(),.n_cols(),.n_elem(). The elements are accessed and assigned with (i,j) operator. Note that the index starts at 0. Element injection: A << 1 << 2 << 3 << endr; (STAT 598W) Lecture 14 25 / 36
Some operators Overloaded operators: +,-,*,%,==, =,!=..trans():transpose, eye(): set an identity matrix. Cholesky decomposition: chol(mat M). You can save memory declaring upper and lower triangular matrices: trimatu and trimatl. Extract columns or rows from a matrix: A.col(k), A.row(k). (STAT 598W) Lecture 14 26 / 36
Exercise Armadillo has the function.randn() to generate standard normal random variables. Generate samples of a multivariate normal random vector with mean µ and covariance matrix Σ, where Σ is positive definite. If you don t have LAPACK installed (e.g. expert server), let s assume we have L such that Σ = LL T. (STAT 598W) Lecture 14 27 / 36
A good tutorial document To learn more about Armadillo, another good material apart from its official website is the document from the following link: http://www.ngssc.se/courses/specialized-courses /advanced-programming/cpp_part3_v2.pdf (STAT 598W) Lecture 14 28 / 36
Outline 1 Some other terms: Namespace and Input/Output 2 Armadillo C++ 3 Application (STAT 598W) Lecture 14 29 / 36
MonteCarlo simulation In the Black-Scholes model we assume that the underlying asset follows a geometric Brownian motion: ds t = µs t dt + σs t dw t where µ and σ > 0 are constants, W t is a standard Brownian Motion and S 0 = s. Using Ito formula, the previous SDE admits the solution: S t = se ) (µ σ2 t+σw 2 t (STAT 598W) Lecture 14 30 / 36
MonteCarlo simulation Under the risk-neutral measure (Q) we can simulate an entire path of S t with the following scheme: S i+1 = S i exp (r σ2 2 )δt + σ δtɛ i+1 where S 0 = s and ɛ. N(0, 1) (iid) Then given a payoff function Φ( ), the price of a derivative with such payoff at time 0 is: Π = E Q [e rt Φ(S T )] (STAT 598W) Lecture 14 31 / 36
MonteCarlo Simulation Then we can use the estimate: ˆΠ = 1 M M e rt Φ(S T (i)) i=1 where S T (i) is the i-th sample path in our simulation. We can reduce the variance in our simulation by using antithetic variates. (STAT 598W) Lecture 14 32 / 36
Variance improvements Improve your rate of convergence by using antithetic variables: use x i N(0, 1) and x i to simulate the GBM and compute (for each one) the simulated price. Then take the average price of both simulations. You can improve the rate of convergence using control variates as well. (STAT 598W) Lecture 14 33 / 36
Exercise Construct a namespace called BS (Black Scholes). It will include the following classes: A base class (Black-Scholes European)(BSEur) with the following members: Constructors. Destructor. Parameters: S, K, r, σ, T and type of option. Black Scholes price. Function that displays the price on the screen. A derived class from BSEur (say MCarlo) with the following members: Constructors. Destructor. Parameters: number of iterations. MonteCarlo price. Function that displays the price on the screen. (STAT 598W) Lecture 14 34 / 36
Exercise A derived class from Mcarlo (say MCAnti) with the following members: Constructors. Destructor. MonteCarlo price (using Antithetic variables). Function that displays the price on the screen. Test your code in C++. Implement your class in R using Rcpp, and compare the sampling distribution of your two estimates. (STAT 598W) Lecture 14 35 / 36
Some recomendations Use Armadillo for your random number generation. Don t forget to define your derived-class constructors as inline functions. (STAT 598W) Lecture 14 36 / 36