- Lab Tutorial 2 Question Paper
- SPAcommprot en C
- Arduino Tutorial 6 Data Types and Structures
- TAREA_[1]
- Text
- 10.009-2016-cohort_wk1
- Dream Weaver Cs5 Shortcuts Mac
- UCSD CSE Advisory Placement Exam
- Iec61131-3 Programmers Manual
- Vulnerability Report (ESF PfSense Status_rrd_graph_img.php Command Injection)
- The Minimum You Need to Know About Mono and Qt
- C Notes
- Computer Science MCQs
- Generic Break out
- b02 Analog
- ModbusASCII Master e
- CSC131 Exercise
- 12 Computer Science Notes Ch2 Introduction to CPP (1)
- 2009-Brouwers-darjeeling
- Written_Directions_for_EV3_Line_Follow (1).pdf
- VHDL Tutorial
- BCA 303 Unit 2 Notes
- 30561-15
- 23612_javalessons
- rk
- 3.Operators Ver2
- Introduction to Java for Begineers
- ibm
- SQL Server Lab 2
- Latex Manual
- Yes Please
- The Unwinding: An Inner History of the New America
- Sapiens: A Brief History of Humankind
- The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution
- Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
- Dispatches from Pluto: Lost and Found in the Mississippi Delta
- Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
- John Adams
- The Prize: The Epic Quest for Oil, Money & Power
- The Emperor of All Maladies: A Biography of Cancer
- This Changes Everything: Capitalism vs. The Climate
- Grand Pursuit: The Story of Economic Genius
- A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
- The New Confessions of an Economic Hit Man
- Team of Rivals: The Political Genius of Abraham Lincoln
- The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
- Smart People Should Build Things: How to Restore Our Culture of Achievement, Build a Path for Entrepreneurs, and Create New Jobs in America
- Rise of ISIS: A Threat We Can't Ignore
- The World Is Flat 3.0: A Brief History of the Twenty-first Century
- Bad Feminist: Essays
- Steve Jobs
- Angela's Ashes: A Memoir
- How To Win Friends and Influence People
- The Sympathizer: A Novel (Pulitzer Prize for Fiction)
- Extremely Loud and Incredibly Close: A Novel
- Leaving Berlin: A Novel
- The Silver Linings Playbook: A Novel
- The Light Between Oceans: A Novel
- The Incarnations: A Novel
- You Too Can Have a Body Like Mine: A Novel
- The Love Affairs of Nathaniel P.: A Novel
- Life of Pi
- The Flamethrowers: A Novel
- Brooklyn: A Novel
- The First Bad Man: A Novel
- We Are Not Ourselves: A Novel
- The Blazing World: A Novel
- The Rosie Project: A Novel
- The Master
- Bel Canto
- A Man Called Ove: A Novel
- The Kitchen House: A Novel
- Beautiful Ruins: A Novel
- Interpreter of Maladies
- The Wallcreeper
- Wolf Hall: A Novel
- The Art of Racing in the Rain: A Novel
- The Cider House Rules
- A Prayer for Owen Meany: A Novel
- Lovers at the Chameleon Club, Paris 1932: A Novel
- The Bonfire of the Vanities: A Novel
- The Perks of Being a Wallflower
- The Constant Gardener: A Novel

Introduction

The idea of this lecture is to get you from possibly knowing nothing about the language to being able to work out the Black-Scholes model in C++. This presentation is of necessity a little skeletal - I will try to get across some key facts and constructions that will get you going as quickly as possible, but you should flesh this out by reading around in due course.

We will use the Bloodshed compiler so start it right away.

Once you have got it started, in a browser navigate to the secure area of the web site:

http://www.mth.kcl.ac.uk/~shaww/web_page/lgs/notes/cppfiles

In here you can find a zip files called cppexamples.zip. Ideally you will download and unzip this file and get all the example programs at once. Otherwise we can retrieve them one at a time, starting with

hello.cpp

from the link indicated under "C++ programming material". Save it in your "My Documents" area or somewhere else you can remember and open it from within Dev C++. This file contains the following program

#include <iostream> using namespace std;

int main() { char name; cout << " Hello Compfin student " << endl; cout << " Hit any key+<RET> to finish \n " ; cin >> name; return(0); }

First we shall compile and run this program, the talk about how it works. Go to the Dev-C++ menu "Execute" and pick the "Compile and Run" option. There is a shortcut which is to just hit F9. Let's get this going....

Comments on this program: 1. The basic C++ system does not have a lot of things you need to get going. So you ALWAYS have to literally "include" some library functions. To comunicate with a terminal (here DOS) window you have the following command, which includes the standard (<>) library iostream. #include <iostream>

Go to the Dev-C++ menu "Execute" and pick the "Compile and Run" option. There is a shortcut which is to just hit F9. Let's get this going.... 2 King's College London Comments on this program: 1. The basic C++ system does not have a lot of things you need to get going. So you ALWAYS have to literally "include" some library functions. To comunicate with a terminal (here DOS) window you have the following command, which includes the standard (<>) library iostream. #include <iostream> 2. The using namespace std; line allows you to use the short form of standard functions such as cout and endl 3. The next line is int main(). All C++ programs have this for the main part of the code. Programs return a value, here an integer denoted int, or nothing, in which case they are declared as void. Here the main block ends with return(0) which means that the program returns the integer zero. 4. All program statements are separated with a semi-colon, ; 5. << is used to separate items in an output stream. 6. Text is delimited with " marks. 7. >> is used to separate items in an input stream. 8. endl ends a line in the output. 9. \n is a newline character you can put in a string of text. 10. To stop this program ending before you can even see what has happened I have put in a line that wants an input in the form of a key stroke; to this end I have declared a character variable name so as to serve as the keystroke variable.

Strings

Close hello.cpp and go and fetch helloname.cpp. Here it is

#include <iostream> #include <string> using namespace std;

int main() { string myname; char keystroke; cout << " What is your name" << endl; cin >> myname; cout << " Hello " << myname << endl ; cout << " Hit any key+<RET> to finish \n" ; cin >> keystroke; return(0); }

If we include the string library we can use a string variable which does NOT require us to specify how long it might be. Your name might be very long for example. Ever had an internet form which stops you typing in your full name or address??

cin >> a >> b. sum = a+b. cout << " Your numbers were " << a << " and " << b << endl .cpp makes this clear. product = a*b.sum. int main() . cout << " Hit any key+<RET> to finish \n" .product.ratio. which has the following code in it: #include <iostream> using namespace std. You just have to name the file.cpp. average = sum/n. Here it is: // This program does some basic arithmetic and writes the result to a file // It has comments like this one! // The double slash denotes precisely one line of comments. #include <iostream> #include <fstream> // The latter include statement allows file management using namespace std. cout << " Their product is " << product << endl . multiplication and division.average. float a.Shaw: LGS Notes. int main() { char keystroke. cout << " Their arithmetical average is " << average << endl . Including one further library makes this possible in exactly the same way you write to the screen.-. cout << " Type in two positive numbers \n" . return(0). } Saving your results to a file You will very rapidly progress to have screenfulls of unsaved data once you get going.*. C++ quickstart 3 Numbers 1: Integers and float types and basic arithmetic So the first thing a Quant needs to be able to do is have numbers and arithmetic in their program. so it is a good idea early on to have a basic idea of writing the results to a file. cout << " Their sum is " << sum << endl . difference = a-b.difference. ratio = a/b. cin >> keystroke. subtraction. SO go and get arithmeticone. int n=2. cout << " Their ratio is " << ratio << endl . The example in arithmeticonefile./ for addition. The simplest relevant data types are int and float and you can do simple arithmetic with the operators +. cout << " Their difference is " << difference << endl . and also adds the idea of putting in comments.b.

b. // Now deal with output to a file . difference = a-b. Now we need to expand our understanding of basic arithmetic and mathematics. (b) complex numbers are not managed as a standard at all (c) there is increasing chaos and variation as you introduce vectors. out << " Their difference is " << difference << endl . Arithmetic and Elementary Mathematics in C++ So at this point you have seen how to do some very basic input and output. We first need to get a grip on the types of numbers. ratio = a/b. int n=2. product = a*b.// The double slash denotes precisely one line of comments. cin >> keystroke. // send the results to it: out << " Your numbers were " << a << " and " << b << endl . return(0). average = sum/n. cin >> a >> b. out << " Their arithmetical average is " << average << endl . int main() { /* If I want my comments to span several lines I use these star-slash delimiters */ char keystroke. 4 #include <iostream> #include <fstream> // The latter include statement allows file management King's College London using namespace std. The matter is frankly somewhat unsatisfactory as (a) the standard for C++ does not enforce differences between type variations that you would imagine is a basic requirement. float a. .average. // Use ordinary terminal output for the closing keystroke cout << " Hit any key+<RET> to finish \n" .hard coded for now: ofstream out("myoutput. } Numbers.sum.txt"). out << " Their sum is " << sum << endl .product. out << " Their product is " << product << endl . out << " Their ratio is " << ratio << endl . basic arithmetic and save the results to a file. matrices and higher order stuff. cout << " Type in two positive numbers \n" .ratio. sum = a+b.difference.

C++ quickstart (a) the standard for C++ does not enforce differences between type variations that you would imagine is a basic requirement. long double num_ld=1. You might like to look up short int and long int and unsigned variations in the notes and in books. For "whole numbers" I will NOT get into the variations on integers and will just use the type "int" everywhere in these notes.precision(20) in order to make it possible to see the difference.grip on the types of numbers. double num_d=1. It is a good idea to run the following code on any system you plan to use to get an idea of what is going on! This is realtypes. cout << " Hit any key+<RET> to finish \n" . For real numbers there are some important things to think about.0/7. : " << 1. There are three basic types: float double long double The C++ standard does not require that these things are necessarily different from one another. int main() { char keystroke.0/7 << endl . matrices and higher order stuff. The matter is frankly somewhat unsatisfactory as 5 Shaw: LGS Notes.0/7. I sneaked in a statement: cout. return(0). You should at some point read up on ranges of numbers and associated issues. cin >> keystroke. cout << " The long double is : " << num_ld << endl . : " << num_d << endl . cout.cpp: #include <iostream> using namespace std. We shall use double everywhere from now on. float num = 1. } If you look at the output it is clear that there is nothing extra in long double in this system. .0/7. cout << " The float is cout << " On the fly gives cout << " The double is : " << num << endl . (b) complex numbers are not managed as a standard at all (c) there is increasing chaos and variation as you introduce vectors. Find out what happens if you comment out this line (Do it NOW!).precision(20).

cout << i << j << k << endl. } You often want to use these shorthands for incrementation in loops/iterations. j=0. you do not have to write i = i+2 rather. . * times. cin >> keystroke.g. return(0).addition.6 King's College London Arithmetical Operations We already looked at the basics of + . k++. int i=0. i=i+1. in which case you would say not i=i+1 or indeed.subtraction. . It is possible to combine these with assignment (= in C++) to write shorter code: So if. / divide. i is an integer and you want to add two to i. Frequently you may be stepping through something in steps of one. int main() { char keystroke. j+=1. not i+=1 but just i++ Run the following example (incrementing. e. k=0. cout << " Hit any key+<RET> to finish \n" . you can say i+=2 Simlarly with the other operators.cpp) just to make sure of things #include <iostream> using namespace std.

let alone stuff like Bessel functions or hypergeometric functions. acos.. the polynomial x2 + x + 1should be worked out NOT with pow(x.. Basic Control Structures in C++ Programs often need to do similar things many times or make choices or do something until a test fails. C++ quickstart 7 "Standard" Maths functions To do just about anything mathematical you will need to load the math library with a statement of the form #include <cmath> at the top of the code. For example. Note that stuff we might consider basic like the cumulative normal distribution is not there. asin. if i and j are integers precisely one of the following is true: i>j i==j i<j but your decisions could also be based on >= or <= for example and note that just as in Mathematica the double equals plays the role of denoting equality. and so on.see www.(ever valued an Asian option?).g. A Boolean statement should be decidable to be true or false..com/reference/clibrary/cmath for some more details cos.. modf pow. sqrt ceil. as opposed to a single = that is used for assignment. tanh exp. The first thing you need to understand is Boolean structures. Rather than doing some boring examples calling various functions we shall see some of them in use later. tan. log..2)+x+1 but rather with 1+x*(1+x) and this type of nesting is always desirable. All of this is managed by a variety of control structures.fmod You have to have this loaded (again!).fabs.cpp that makes a simple comment about the size of a number and accordingly decides to square or cube it: . sin. atan2 cosh. log10. Don't get lazy with these functions. and these are best illustrated by their use within an if statement. atan. ifdeciding.. E. Just about every program will want to have this loaded as it contains the really basic stuff like sqrt for square root! Here are the most useful bits . sinh.cplusplus.floor.Shaw: LGS Notes. Here is a simple program.

cin >> keystroke.8 King's College London If then else example #include <iostream> /* This program illustrates the use of the if statement. blocks are grouped with {}. You need to explicitly "break" out of the tests once you have carried out the branch of interest. cout << "its square is " << i*i << endl.} cout << "Hit any key+<RET> to finish \n" . But if you have three or more possibilities to contend with it MIGHT be more elegant to use the "switch" structure PROVIDED the choices can be simplified to just matching to a finite set of constants. switch (i) { case 1: cout << "You entered one \n". int i. } Switch case example You can of course build up some complicated logic based on a collection of if-else statements. . */ using namespace std. int main() { char keystroke. Note: A. int i. This can be particularly useful if you have an algorithm that may take simple forms for certain paramaters otherwise it reverts to a general system. cout << " Enter a positive integer \n ". return(0). else is optional */ using namespace std.cpp #include <iostream> /* This program illustrates the use of the switch case statement. cout << " Enter an integer \n ". cout << "its cube is " << i*i*i << endl. if (i>= 100) {cout << "that is quite a big number \n". Go get switchdeciding. cin >>i.} else {cout << "that is not a big number \n". int main() { char keystroke. cin >>i. B.

case 3: cout << "You entered three \n".{ Shaw: LGS Notes. y = x/2+c/(2*x). break. switch (i) { case 1: cout << "You entered one \n". . y=1. } char keystroke. break. return(0). break. cout << " Enter a positive integer \n ". C++ quickstart int i. cout << " Enter a positive number \n ". case 4: cout << "You entered four \n". cin >> c. cout. A program might keep executing "While" an error is bigger than some tolerance. } cout << "the square root of your number is " << y <<endl. 9 While examples This is very important in financial maths as it is frequently used in iterative processes. } cout << "Hit any key+<RET> to finish \n" . while (x!=y) { x=y.precision(20). default: cout << "You entered something other than one to four\n". The first is whileiteration. If we input a number c and want to solve the equation f HxL = x2 . cin >>i. double c.c 0 (1) This equation may be solved iteratively by Newton-Raphson methods with the scheme xn-1 c xn ÅÅÅÅÅÅÅÅÅÅÅÅÅ + ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ Å Å 2 2 xn-1 We will give two programs to solve this. cin >> keystroke. case 2: cout << "You entered two \n". break. break. for example to solve an equation numerically.0. */ using namespace std. x. (2) int main() { char keystroke.cpp and is as follows: #include <iostream> /* This program uses the while statement to solve an equation iteratively. A classic example would be to find the square root of a number.

int main() { char keystroke. } . return(0). The termination criteris is now set more tolerantly with the fabs math function. cout << "Hit any key+<RET> to finish \n" . in which case the following slightly cruder while statement would be used. cout << " Enter a positive number \n ".0. while (x!=y) { x=y.0e-2) { x=y. y = x/2+c/(2*x). while (fabs(x-y)>1. 10 cin >> c. y = x/2+c/(2*x). } cout << "the square root of your number is " << y <<endl.precision(20). y=1.cout << " Enter a positive number \n ". King's College London } It will often be the case that you want to stop at a certain pre-defined tolerance. cout << "its square gives back " << y*y << endl. */ using namespace std. cin >> keystroke. This is a very common construction. x. cin >> c. double c. cin >> keystroke. } cout << "the square root of your number is " << y <<endl. cout. cout << "Hit any key+<RET> to finish \n" . This is whileiterationcruder. cout << "its square gives back " << y*y << endl. return(0).cpp: #include <iostream> #include <cmath> /* This program uses the while statement to solve an equation iteratively.

cin >> c.0. int main() { char keystroke. cout << "Hit any key+<RET> to finish \n" . as in the above example. return(0). and the loop keeps on executing until the test fails. y = x/2+c/(2*x). C++ quickstart 11 Do-While example Note that in the examples of while the execution might never take place . cout << "the square root of your number is " << y <<endl.0e-2). } . cout << "its square gives back " << y*y << endl. x. double c.the test is at the beginning. do { x=y. */ using namespace std. But let's just rewrite our solver to use do while to see it working! This is dowhileiteration.precision(20).cpp #include <iostream> #include <cmath> /* This program uses the do while statement to solve an equation iteratively. } while (fabs(x-y)>1. You can usually achieve this within an ordinary while by initialising matters suitably. y=1. cout << " Enter a positive number \n ". cin >> keystroke.Shaw: LGS Notes. The commands will always run at least once. There is a variation on this which says do {commands} while (test). cout.

for the partial derivatives. #include <iostream> /* This program uses the for statement to table some numbers */ using namespace std. To get going on e. cout << "cube " << i*j << ".cpp we outupt powers of the integers from 0 to 9. } Simple User-Defined Functions in C++ There are many levels at which one can consider this topic.12 King's College London For loops These can be used to do all types of numerical modelling where one wants to set up tree or finite-difference models and work around a grid.g. Rather than faff with some contrived basic examples let's go straight for the Normal Distribution function first. int main() { char keystroke. } cout << "Hit any key+<RET> to finish \n" . e. return(0). . In foriteration. 2. A function for the Black-Scholes formula. int i. i<10.g. cin >> keystroke. A function for the cumulative Normal Distribution. square "<< j << endl. working out the Black-Scholes model we really need two functions 1. The we shall have a function calling this function which may as well be the Black-Scholes model. for (i=0. The latter can be extended to all kinds of other functions. For now we just see its use in setting up a loop of a DEFINED length.j. fourth power " << j*j << endl. i++) { j=i*i. cout << "number " << i << ".

} We have these two functions together in a program where the main block works out the values of the CDFs with the two models and outputs them to a file.org/v11/i04/v11i04. I have deleted a couple of blocks not relevant to this discussion.5*q-0.i=1. Note that Joshi (a) takes special care of the tails (b) works out the polynomial piece more efficiently.b=x.cpp.jstatsoft. return 0.2.398942280401433.q=x*x. while(s≠t) s=(t=s)+(b*=q/(i+=2)).Shaw: LGS Notes.5+s*exp(-0.pdf and he came up with a C programme based on the result that This has been known for a long time (see formula 26.11 of Abramowitz and Stegun).cpp: // CumulativeNormals. . Joshi (though he has said he used something else professionally!).ÅÅÅÅ2ÅÅÅÅÅ jx + ÅÅÅÅÅÅÅÅ + ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ + ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ ÅÅÅÅÅÅ + ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ ÅÅÅÅÅÅÅÅÅÅÅÅ + …z Å Å ÅÅÅÅ ÅÅÅÅÅÅÅÅ Å è!!!!!!! 2 3 3µ5 3µ5µ7 3µ5µ7µ9 k { 2p (3) {long double s=x. Here is the c code for it: double PhiMarsaglia(double x) xÅ2 i 1 1 x3 x5 x7 x9 y j z FHxL = ÅÅÅÅÅ + ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ ‰. Vol 11 Issues 4). July 2004.t=0. available on the web at: www.91893853320467274178L). const double phinorm = 0. The code is cumulativenormals. Marsaglia in 2004 (Journal of Statistical Software.cpp // code to work out the normal pdf and cdf // the latter via a rational approximation (Joshi's code) and Marsaglia's series //First include is all that is needed for function definitions // Rest is for I/O #include <cmath> #include <iostream> #include <fstream> using namespace std. // phinorm is constant value of one over root 2 pi. Marsalglia's Series The matter of approximating the cumulative Normal was revisited and surveyed by G. C++ quickstart 13 Joshi's and Marsaglia's C++ Implementation of the Normal CDF A C++ version of the second rational approximation has been made publicly available by M. Below in the program I haved included the relevant extract from Normals. downloadable from his web site (the link to it is in the /notes/ directory).

// phinorm is constant value of one over root 2 pi. else { double tmp = 1.2316419*fabs(x)). -0. 1.0-result. } /* code for PhiRational is renamed version of * code Copyright (c) 2002 * Mark Joshi * * Permission to use.0 .330274429}.+x*x). if (x<=0. copy. else { if (x>7.319381530.0+0. } } return result. 1. const double phinorm = 0.356563782.821255978. distribute and sell this .0) result = phi(x)/sqrt(1.PhiRational(-x). if (x<-7. modify. // pdf double phi(double x) { return phinorm*exp(-x*x/2).0) result = 1. double result.781477937.398942280401433. result=1-phi(x)* (tmp*(a[0]+tmp*(a[1]+tmp*(a[2]+tmp*(a[3]+tmp*a[4]))))).#include <iostream> 14 #include <fstream> King's College London using namespace std. -1.0) result=1. } double PhiRational(double x) { static double a[5] = { 0.0/(1.

double x. cout << "Marsaglia approximation (Marsaglia implmentation) \n". cin >> range. int N. copy. while(s!=t) s=(t=s)+(b*=q/(i+=2)). provided that the above copyright notice * appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation.txt \n " << endl. int main() { double result. cout << "Enter range parameter (range) \n ". modify. int j.91893853320467274178L) . char keystroke.i=1. double marsphi.b=x. */ } 15 /* The following is the compact code provided by Marsaglia in his 2004 paper! */ double PhiMarsaglia(double x) {long double s=x. cout << "Test computations of cumulative normal distributions \n ". It is provided * "as is" without express or implied warranty. distribute and sell this * software for any purpose is hereby * granted without fee. cout << "Enter number of positive and negative sample points (N) \n ".5+s*exp(-0. return 0. double ratphi. cout << " Result being written to normaloutput. . double range. cout << "Rational approximation (Joshi implementation) \n".t=0.q=x*x.5*q-0. Shaw: LGS Notes. C++ quickstart /* code for PhiRational is renamed version of * code Copyright (c) 2002 * Mark Joshi * * Permission to use. } #include <iostream> #include <cmath> using namespace std. * Mark Joshi makes no representations about the * suitability of this software for any purpose.return result. cin >> N.

hello. foriteration. This code runs both the rational approximation and the Marsaglia formula over the range and outputs triples {x. ratphi = PhiRational(x).cpp. normaloutput. arithmeticone.cpp and look at the output.exe.cpp.exe. 16 cout << "Marsaglia approximation (Marsaglia implmentation) \n".cpp.cpp.cpp. 3D. cin >> range.cpp< cnormaldata = ReadList@"normaloutput. len = Length@tabularD 2001 . NumberD. out.txt. whileiteration. helloname.exe. blackscholes. Marsaglia(x)}.cpp. switchdeciding.cpp.zip. King's College London ofstream out("normaloutput. cppexamples.txt.cpp. } We proceed to compile and run the C code cumulativenormals.cpp. tabular = Partition@cnormaldata. dowhileiteration. arithmeticonefile. cumulativenormals. whileiterationcruder. for (j=0. realtypes.cpp. ifdeciding. rational(x). myoutput.nb. } cout << "Hit any key+<RET> to finish \n" .exe. incrementing.cpp.cout << "Rational approximation (Joshi implementation) \n". j<= 2*N.exe. with N=1000. cumulativenormals.txt"). marsphi = PhiMarsaglia(x). helloname. arithmeticonefile. cin >> N. out << x << " " << ratphi << " " << marsphi << "\n". Lecture3_pottedCPP. j++) { x = -range + j*range/N. cin >> keystroke. return(0).cpp.precision(15). cout << "Enter range parameter (range) \n ".cpp.txt \n " << endl. cout << "Enter number of positive and negative sample points (N) \n ". hello. SetDirectory@ "C:\Documents and Settings\William Shaw\My Documents\LGS0708"D C:\Documents and Settings\William Shaw\My Documents\LGS0708 FileNames@D 8arithmeticone.txt". range = -7 to 7. cout << " Result being written to normaloutput.

HFuncTwoBase@xD.6 0. e = 1.4 0. 8i. Ncdf[x_] := (1 + Erf[x/Sqrt[2]])/2 HFuncTwoBase@x_D := Module@8g = 0.Shaw: LGS Notes. 2DD<.821255978.2316419.5]. 3DD<.330274429. tabular@@i.319381530. HFuncTwoBase@-xDD . C++ quickstart 17 ratdata = Table@8tabular@@i. b = -0. 1 0. a = 0.5*Erf[z/Sqrt[2]] + 0. ListPlot@ratdataD. 1 0.8 0. tabular@@i. u = Exp@-x ^ 2 ê 2D ê Sqrt@2 PiD * Ha * k + b * k ^ 2 + c * k ^ 3 + d k ^ 4 + e k ^ 5LD HFuncTwo@x_D := If@x >= 0. k = 1 ê H1 + g xL. d = -1.2 -6 -4 -2 2 4 6 marsdata = Table@8tabular@@i. 1.4 0.356563782. 8i. I will reload some Mathematica implementations for comparison. len<D. 1DD.6 0. ListPlot@marsdataD.8 0.781477937.how are we going to check them out for quality and correctness of the implementation. len<D. Ncdf[(z_)?NumberQ] := N[0. c = 1.2 -6 -4 -2 2 4 6 These look OK . 1DD. 1 . 1. k<.

1 ê 2 + s ê Sqrt@2 PiD Exp@-q ê 2DD ratcomp = Table@8tabular@@i. i = 1<. len<D. 1. ListPlot@ratcomp.5µ 10 -1µ 10 -16 -16 -16 -15 -16 -16 -16 2 4 6 .5µ 10 -5µ 10 -7. len<D.5µ 10 5µ 10 2.18 King's College London ‡ Joshi vs Mathematica on the rational approximation MarsagliaNcdf@x_D := Module@8s = x. 1DDD tabular@@i. t = 0. PlotJoined Ø TrueD. PlotJoined Ø TrueD. 5µ 10 -16 -6 -4 -2 -16 2 4 6 -5µ 10 -1µ 10 -15 So these are indeed the SAME rational approximation! ‡ Marsaglia vs Mathematica Marsaglia on the series approximation marscomp = Table@8tabular@@i. 8i. s = t + bLD. 7. 8i. 1. MarsagliaNcdf@tabular@@i. Ht = s. q = x * x. 1DDD . 1DD. ListPlot@marscomp. 3DD<. While@Abs@Hs . HFuncTwo@tabular@@i.tabular@@i.tLD > 10 ^ H-19L. b = x. b *= q ê Hi += 2L. 1DD. 2DD<.5µ 10 -6 -4 -2 -2.

1DDD .tabular@@i. General::spell1 : Possible spelling error: new symbol name "ratcompb" is similar to existing symbol "ratcomp". len<D. PlotJoined Ø TrueD. First we do built in Mathematica Phi against the C code with the rational approximation: ratcompb = Table@8tabular@@i. 1. 1DD. . 8i. C++ quickstart 19 So these are indeed there to as much precision as we care about. PlotJoined Ø TrueD. Two more comparison of Mathematica's built in gadget against the external C. 1DD. More… -8 -8 -8 6µ 10 4µ 10 2µ 10 -6 -4 -2 -2µ 10 -4µ 10 -6µ 10 2 -8 -8 -8 4 6 marscompb = Table@8tabular@@i. 1. len<D. Ncdf@tabular@@i. Ncdf@tabular@@i.Shaw: LGS Notes. 2DD<.tabular@@i. 8i. ListPlot@marscompb. 4µ 10 2µ 10 -16 -16 -6 -4 -2 -2µ 10 -4µ 10 -16 2 4 6 -16 This is about as far as I can be bothered to go! The Marsaglia function will do just fine. 3DD<. 1DDD . ListPlot@ratcompb.

398942280401433. } double BSPut(double S. T = 2 // blackscholes.5*sd*sd)/sd.5*sd*sd)/sd. return K*exp(-r*t)*PhiMarsaglia(-d2)-S*exp(-q*t)*PhiMarsaglia(-d1). double K.2. double q. return 0.91893853320467274178L). // pdf double phi(double x) { return phinorm*exp(-x*x/2). double t) { double sd = sigma*sqrt(t). double q. } /* The following is the compact code provided by Marsaglia in his 2004 paper! */ double PhiMarsaglia(double x) {long double s=x.05.1.5+s*exp(-0. const double phinorm = 0. K = 100. r = 0. q = 0. double r.5*q-0.t=0. double sigma. double d2 = d1-sd. while(s!=t) s=(t=s)+(b*=q/(i+=2)). double d1 =(log(S/K)+(r-q)*t+0. return S*exp(-q*t)*PhiMarsaglia(d1)-K*exp(-r*t)*PhiMarsaglia(d2). } . double r. double K.i=1. double d1 =(log(S/K)+(r-q)*t+0.cpp // code to work out the standard model using // Marsaglia's normal function #include <cmath> #include <iostream> #include <fstream> using namespace std.q=x*x. vol = 0. double sigma.20 King's College London Black-Scholes Modelling in C++ Go run the following .b=x.coding the model is easy (error-checking on inputs aside) once you have a decent normal CDF.} double BSCall(double S. double t) { double sd = sigma*sqrt(t). double d2 = d1-sd.

out. return K*exp(-r*t)*PhiMarsaglia(-d2)-S*exp(-q*t)*PhiMarsaglia(-d1). double s. bsp = BSPut(s. cout << "Enter range parameter (range) for prices above and below strike \n ". int main() { double result.5*sd*sd)/sd. cout << "Enter continuous yield (continuously compounded) \n ". cout << " Result being written to bsoutput. double K. bsc = BSCall(s.q. double d2 = d1-sd.k. double sigma. j++) { s = k -range + j*range/N. double q.txt").precision(15). j<= 2*N. double vol.t). char name[5].q.vol. int j.txt \n " << endl. out << s << " " << bsc << " " << bsp << "\n". cout << "Enter risk-free rate (continuously compounded) \n ". cout << "Enter time to maturity in years \n ".double BSPut(double S.k.t). double range.r. ofstream out("bsoutput. cout << "Marsaglia's method for Phi \n". double q. } { 21 using namespace std. C++ quickstart double sd = sigma*sqrt(t). double d1 =(log(S/K)+(r-q)*t+0. cout << "Enter number of positive and negative sample points (N) \n ". cin >> r.r. for (j=0. double bsc. cin >> q.vol. double bsp. } . cin >> range. cin >> vol. cout << "Enter volatility \n ". double r. int N. double k. double t. double r. cout << "Test computations of Black-Scholes pricing \n ". cout << "Enter strike \n ". cin >> t. cin >> N. double t) Shaw: LGS Notes. cin >> k.

exe. helloname. len = Length@tabularD 2001 bscdata = Table@8tabular@@i.exe. out << s << " " << bsc << " " << bsp << "\n". hello.cpp.cpp< bsdata = ReadList@"bsoutput.for (j=0.q. 2DD<. } King's College London return(0). } SetDirectory@ "C:\Documents and Settings\William Shaw\My Documents\LGS0708"D C:\Documents and Settings\William Shaw\My Documents\LGS0708 FileNames@D 8arithmeticone.cpp. cumulativenormals.cpp. helloname. cppexamples.exe. tabular@@i. cumulativenormals. dowhileiteration. ListPlot@bscdataD. arithmeticonefile. j++) 22 { s = k -range + j*range/N. bsc = BSCall(s. normaloutput. incrementing. myoutput.cpp.cpp.q.txt.k. j<= 2*N.cpp.r. foriteration.zip. switchdeciding. tabular = Partition@bsdata.cpp.exe. arithmeticone.t).txt.vol.txt".cpp. 8i. blackscholes. arithmeticonefile.nb. Lecture3_pottedCPP. 1DD.r. hello.t). out. whileiteration.vol.cpp.precision(15). NumberD. 1.k.cpp. ifdeciding. bsp = BSPut(s. realtypes.exe.cpp. whileiterationcruder.cpp.cpp. 35 30 25 20 15 10 5 80 90 100 110 120 130 . len<D. 3D.

r. t_] := k*Exp[-r*t]*Ncdf[-dtwo[s. r_. tabular@@i. q_] := Log[s/k])/(s*Sqrt[t]) + (s*Sqrt[t])/2. q_] := Log[s/k])/(s*Sqrt[t]) . s_. C++ quickstart 23 done[s_. k_. s. s_.s*Exp[-q*t]*Ncdf[-done[s. k_. ListPlot@callerrorcheck. q]] callerrorcheck = Table@8tabular@@i. PlotJoined Ø TrueD. t. 0. ((r . len<D. q_. r_.2. s. s_. 0. 1. t.k*Exp[-r*t]*Ncdf[dtwo[s. 1DD. t_] := s*Exp[-q*t]*Ncdf[done[s. 2D tabular@@i. r. s_.q)*t + dtwo[s_. t. 1DD. s. 100. BlackScholesPut[s_. 1DD. ((r .q)*t + k_. k. BlackScholesCall[s_. q]]. r_. t_. 8i. 2DD<. t. t_. 6µ 10 4µ 10 2µ 10 -14 -14 -14 -2µ 10 -4µ 10 -6µ 10 -8µ 10 -14 -14 -14 -14 80 90 100 110 120 130 20 bspdata = Table@8tabular@@i. q]] .05. k. 0. ListPlot@bspdataD. q]] .1. 1. s. r_. BlackScholesCall@tabular@@i.Shaw: LGS Notes. q_. r. k_. k. 8i.(s*Sqrt[t])/2. r. 3DD<. 15 10 5 80 90 100 110 120 130 . k. len<D.

8i. 1DD.1. 0. PlotJoined Ø True. 0. 1. ListPlot@puterrorcheck. PlotRange Ø AllD. BlackScholesPut@tabular@@i.2. 2D tabular@@i. 100. 6µ 10 4µ 10 2µ 10 -14 -14 -14 80 -2µ 10 -4µ 10 -6µ 10 -14 -14 -14 90 100 110 120 130 . 0. len<D. 3DD<. 1DD.24 King's College London puterrorcheck = Table@8tabular@@i.05.

- Lab Tutorial 2 Question PaperUploaded byOikhian Chan
- SPAcommprot en CUploaded byNermina Malićević
- Arduino Tutorial 6 Data Types and StructuresUploaded bydariohot21
- TAREA_[1]Uploaded byCaroNatitaEscalierSandoval
- TextUploaded byisrajuddin
- 10.009-2016-cohort_wk1Uploaded byJia Ying
- Dream Weaver Cs5 Shortcuts MacUploaded bySean Kelly
- UCSD CSE Advisory Placement ExamUploaded byWendy Kwan
- Iec61131-3 Programmers ManualUploaded byrfxfkjd
- Vulnerability Report (ESF PfSense Status_rrd_graph_img.php Command Injection)Uploaded bycostachemariusalin1704
- The Minimum You Need to Know About Mono and QtUploaded byRoland Hughes
- C NotesUploaded byAbhinandan Maity
- Computer Science MCQsUploaded byRoshan Zamir
- Generic Break outUploaded byiamausten
- b02 AnalogUploaded byMike George
- ModbusASCII Master eUploaded bySocaciu Viorica
- CSC131 ExerciseUploaded bykakpisz
- 12 Computer Science Notes Ch2 Introduction to CPP (1)Uploaded byitsv4v
- 2009-Brouwers-darjeelingUploaded byjoseph.stewart9331
- Written_Directions_for_EV3_Line_Follow (1).pdfUploaded byEvandro Andrade
- VHDL TutorialUploaded byAracely Chico
- BCA 303 Unit 2 NotesUploaded byVinay Garg
- 30561-15Uploaded byapi-3698966
- 23612_javalessonsUploaded byadriel_25
- rkUploaded byMoumita Bera
- 3.Operators Ver2Uploaded byqwernasd
- Introduction to Java for BegineersUploaded byGihanRannulu
- ibmUploaded byAgni Dev
- SQL Server Lab 2Uploaded byLua
- Latex ManualUploaded bycd_levy