Lecture 14. Xiaoguang Wang. March 11th, 2014 STAT 598W. (STAT 598W) Lecture 14 1 / 36

Similar documents
C++ Scope Resolution Operator ::

Input and Output File (Files and Stream )

Programming II with C++ (CSNB244) Lab 10. Topics: Files and Stream

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

BITG 1113: Files and Stream LECTURE 10

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

10. Functions (Part 2)

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Unit 1 : Principles of object oriented programming

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Chapter 14 Sequential Access Files

Objects and streams and files CS427: Elements of Software Engineering

C++ for Python Programmers

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

UEE1303(1070) S 12 Object-Oriented Programming in C++

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

UNIT V FILE HANDLING

CS2141 Software Development using C/C++ Stream I/O

Simple File I/O.

Week 5: Files and Streams

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

C++ Programming Lecture 10 File Processing

Writing a Good Program. 7. Stream I/O

CSCE 206: Structured Programming in C++

EP241 Computing Programming

Object Oriented Programming In C++

Scientific Computing

W3101: Programming Languages C++ Ramana Isukapalli

C++ does not, as a part of the language, define how data are sent out and read into the program

Lecture 3 The character, string data Types Files

Short Notes of CS201

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS201 - Introduction to Programming Glossary By

A <Basic> C++ Course

Chapter 12. Streams and File I/O

Developed By : Ms. K. M. Sanghavi

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Binomial pricer (1.1)

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Chapte t r r 9

A <Basic> C++ Course

Object-Oriented Programming in C++

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

File I/O CS 16: Solving Problems with Computers I Lecture #9

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

Types of files Command line arguments File input and output functions Binary files Random access

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Fall 2017 CISC/CMPE320 9/27/2017

CS101 Linux Shell Handout

Object Oriented Programming

Object Oriented Design

Summary of basic C++-commands

Absolute C++ Walter Savitch

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Lecture 7. Log into Linux New documents posted to course webpage

CSI33 Data Structures

What we will learn about this week:

File I/O Christian Schumacher, Info1 D-MAVT 2013

Introduction to C++ (Extensions to C)

C++_ MARKS 40 MIN

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

IS 0020 Program Design and Software Tools

CS201 Latest Solved MCQs

2. It is possible for a structure variable to be a member of another structure variable.

CS11 Intro C++ Spring 2018 Lecture 3

C++ For Science and Engineering Lecture 12

Lecture 14: more class, C++ streams

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CS 103 Unit 14 - Streams

CS 103 Unit 14 - Streams

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Fast Introduction to Object Oriented Programming and C++

Lecture 18 Tao Wang 1

COMP322 - Introduction to C++

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

2 nd Week Lecture Notes

Reading from files File errors Writing to files

cs3157: c++ lecture #2 (mon-11-apr-2005) chronology of some programming languages... C++ vs Java identifiers.

C++ 프로그래밍실습. Visual Studio Smart Computing Laboratory

CS Software Engineering for Scientific Computing. Lecture 5: More C++, more tools.

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Stream States. Formatted I/O

Engineering Tools III: OOP in C++

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Getting started with C++ (Part 2)

Transcription:

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