Top Banner
1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C+ +, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli Kaplunovsky, [email protected], (408) 309 4506
28

1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

Dec 21, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

1

C workshop #5

Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision

By: Yuli Kaplunovsky, [email protected], (408) 309 4506

Page 2: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

2

fopen, fprintf, fclose

• Use ‘pointer’ to predetermined structureFILE *F;

• To create / open file: F = fopen( “file_name”, “type” );examples:F = fopen(“file1.dat”, “w” );F_Read = fopen(“file2.dat”,”r” );

• ALWAYS need to close the file before program terminatesfclose( F );

• One way to write to a file – very similar to printf();fprintf( F, “test\n” );

Page 3: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

3

File write example #1

#include <stdio.h>

void main(){ FILE *F; int I;

F = fopen("file1.dat", "w" ); fprintf( F, "ABCDE\n" ); fprintf( F, "Second Line\n" );

for ( I = 0 ; I < 10 ; I++ ) fprintf( F, "%d, ", I);

fclose(F);}

A new file by the name ‘file1.dat’ is created, and its content is:

ABCDE

Second Line

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

Page 4: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

4

File read example #2

Output (on the monitor):Reading from the file:10, 20, 30, 40, 99, 32, 1, 999, -22, 4423,

#include <stdio.h>

void main(){ FILE *F; int I, J;

F = fopen("num10.dat", "rt" ); printf("Reading from the file:\n"); for ( I = 0 ; I < 10 ; I++ ) { fscanf( F, "%d" , &J ); printf( "%d, ", J ); }

fclose(F);}

The content of the file ‘num10.dat’:

1020304099321999-224423

Page 5: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

5

The content of the file ‘num10.dat’:

1,10.23, 205, 30.331,222 , 33345,469 40.113,-993.333399,33.2

Output (on the monitor):Reading from the file:1,10.23,205,30.331,222,245,469,463,-993.333

#include <stdio.h>void main(){ FILE *F; int I, J; char ST[200]; float FL; double D; F = fopen("num20.dat", "rt" ); printf("Reading from the file:\n"); for ( I = 0 ; I < 8 ; I++ ) { fgets( ST, sizeof(ST)-1, F ); sscanf( ST, "%d,%f" , &J, &FL ); D = FL; printf( "%d,%g \n", J, D ); } fclose(F);}

File read example #3

Page 6: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

6

malloc / free#include <stdlib.h>

void main()

{

double *D;

int I;

D = (double *)malloc( sizeof(D) * 100 );

for ( I = 0 ; I < 100 ; I++ )

D[I] = (double)I * 1.2;

free(D);

}

Page 7: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

7

#include <stdio.h>#include <stdlib.h>#include <math.h>

typedef struct { double X,Y; } CORD_typedef;

int Generate_Sin_Noise( int N, char *FileName ){ FILE *F; int I; CORD_typedef *C;

F = fopen(FileName, "w" ); if ( F == NULL ) return -1; // An Error

C = (CORD_typedef *) malloc( sizeof(CORD_typedef) * N ); if ( C == NULL ) { fclose(F); return -1; // An Error }

for ( I = 0 ; I < N ; I++ ) { C[I].X = (double)I / 30; C[I].Y = ((I==0)? 0 : C[I-1].Y) / 10.0 + (double)(rand() % 1001) / 100 + sin( C[I].X ) * 3.0; }

for ( I = 0 ; I < N ; I++ ) fprintf( F, "%g,%g\n", C[I].X, C[I].Y );

fclose(F); delete(C); return 0;}

void main() { if ( Generate_Sin_Noise( 200, "TestSin.dat" ) != 0 ) { printf("Error\n"); exit(-1); } printf("Done \n");}

Write file example

Page 8: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

8

Page 9: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

9

Page 10: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

10

Page 11: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

11

Page 12: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

12

Page 13: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

13

Page 14: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

14

From excel to C#include <stdio.h>

void main(){ FILE *F; char ST[300]; int ItemsNum,I; struct { int Month; double P1,P2; } Item[1000];

float F1,F2;

F = fopen("Book1.txt", "rt" ); if ( F == NULL ) { printf("Error opening file\n"); return; } fgets(ST, sizeof(ST), F); // We know that the first line is not used

ItemsNum = 0; while ( !feof(F) && ItemsNum < 1000 ) { fscanf( F, "%d %g %g\n" , &(Item[ ItemsNum ].Month), &F1, &F2 ); Item[ ItemsNum ].P1 = F1; Item[ ItemsNum ].P2 = F2; ItemsNum++; } fclose(F);

for ( I = 0 ; I < 3 ; I++ ) printf("%d: %d, %g, %g\n", I, Item[ I ].Month, Item[ I ].P1, Item[ I ].P2 );

for ( I = ItemsNum-5 ; I < ItemsNum ; I++ ) printf("%d: %d, %g, %g\n", I, Item[ I ].Month, Item[ I ].P1, Item[ I ].P2 );

}

Output:0: 192606, -12.31, 0.881: 192607, -19.3, -6.242: 192608, -13.04, -2.83889: 200007, -3.55, 1.72890: 200008, -5.91, -5.17891: 200009, -10.62, -7.07892: 200010, -5.03, 1.58893: 200011, -5.7251, 0.245714

Page 15: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

15

Page 16: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

16

Page 17: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

17

C++ object oriented programming• Reusable code

• Abstract Data Types

• Encapsulate not necessary information

• MFC - Microsoft Foundation Classes

• But... Still it is almost the same C

Page 18: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

18

Examples#include <iostream.h> /* This is the stream definition file */

void print_it(int data_value);

main()

{

int index,top; /* A normal C variable */

cout << "Input a decimal value --> ";

cin >> top;

for (index = 0 ; index < 5 ; index++)

print_it(index);

}

void print_it(int data_value)

{

cout << "The value of the index is " << data_value << "\n";

}

Page 19: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

19

class#include <iostream.h>

class vehicle {protected: int wheels; float weight;public: void initialize(int wheels, float weight); int get_wheels(void); float get_weight(void); float wheel_loading(void);};

// initialize to any data desiredvoid vehicle::initialize(int wheels, float weight){ wheels = in_wheels; weight = in_weight;}

// get the number of wheels of this vehicleint vehicle::get_wheels(){ return wheels;}

// return the weight of this vehiclefloat vehicle::get_weight(){ return weight;}

// return the weight on each wheelfloat vehicle::wheel_loading(){ return weight/wheels;}

void main(){vehicle motorcycle, truck, sedan;

motorcycle.initialize(2, 900.0); truck.initialize(18, 45000.0); sedan.initialize(4, 3000.0); cout << "The truck has a loading of " << truck.wheel_loading() << " pounds per wheel.\n";

cout << "The motorcycle weighs " << motorcycle.get_weight() << " pounds.\n";

cout << "The sedan weighs " << sedan.get_weight() << " pounds, and has " << sedan.get_wheels() << " wheels.\n";}

Output:The truck has a loading of 2500 pounds per wheel.The motorcycle weighs 900 pounds.The sedan weighs 3000 pounds, and has 4 wheels.

Page 20: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

20

inheritanceclass car : public vehicle { int passenger_load;public: void initialize(int in_wheels, float in_weight, int people = 4); int passengers(void);};

void car::initialize(int in_wheels, float in_weight, int people){ passenger_load = people; wheels = in_wheels; weight = in_weight;}

int car::passengers(void){ return passenger_load;}

void main(){ car Mercedes; Mercedes.initialize(4, 3500.0, 5); cout << "The Mercedes carries " << Mercedes.passengers() << " passengers.\n"; cout << "The Mercedes weighs " << Mercedes.get_weight() << " pounds.\n"; cout << "The Mercedes's wheel loading is " << Mercedes.wheel_loading() << " pounds per tire.\n\n";}

Output:The Mercedes carries 5 passengers.The Mercedes weighs 3500 pounds.The Mercedes's wheel loading is 875 pounds per tire.

Page 21: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

21

Newton Raphson method

Page 22: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

22

Page 23: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

23

#include <stdio.h>#include <math.h>

double Func( double X ) { return X*X-5;}

double Newton_Raphson( double start, double accuracy ){ double X,Der; int Loop = 0; X = start; while ( fabs( Func(X) ) > accuracy ) { Der = (Func(X+0.001) - Func(X)) / 0.001; printf("X=%g, Func(X)=%g, Der=%g \n", X, Func(X), Der ); X = X - Func(X) / Der; if ( Loop++ > 20 ) { printf("There might be problem in finding a solution\n"); return X; } } return X;}

void main() { double D; D = Newton_Raphson( 2, 1e-6 ); printf("The solution to Func(X)=0 is: X=%g\n", D );}

Output:X=2, Func(X)=-1, Der=4.001X=2.24994, Func(X)=0.0622188, Der=4.50X=2.23611, Func(X)=0.000204919, Der=4.The solution to Func(X)=0 is: X=2.23607

Page 24: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

24

Page 25: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

25

#include <math.h>

void choldc(float **a, int n, float p[])

{

void nrerror(char error_text[]);

int i,j,k;

float sum;

for (i=1;i<=n;i++) {

for (j=i;j<=n;j++) {

for (sum=a[i][j],k=i-1;k>=1;k--)

sum -= a[i][k]*a[j][k];

if (i == j) {

if (sum <= 0.0) nrerror("choldc failed");

p[i]=sqrt(sum);

}

else

a[j][i]=sum/p[i];

}

}

}

Page 26: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

26

Quiz - Question #1You are asked to write a program that produces the following diamond shape.

Try to minimize the number of printf functions.

ONE PRINTF FUNCTION IS ALLOWED TO DISPLAY ONLY ONE CHARACTER, like printf(" "), or

printf("*"), or printf("\n"), but not printf("*\n***\n*****\n");

*

***

*****

*******

*********

*******

*****

***

*

Page 27: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

27

Question # 2

we want to count the number of primes between 2 and 100000. We will use an algorithm, which works as

follows:

Start with 2. Mark 4,6,8,10,...,100000, which are multiples of 2, as non-primes

(you must find a way in C language to "mark" these numbers)

Next is 3. Mark 6,9,12,15, ..., 99999.

Then 4, 5, 6, ..., until 100000/2=50000.

Those unmarked numbers must be primes (why?).

Page 28: 1 C workshop #5 Files, Interface to Excel & Matlab, Introduction to C++, More Financial Applications (Newton-Raphson), Cholesky decomposision By: Yuli.

28

Question # 3

Write a program to determine how many months it takes to pay off the purchase of a

$1000 stereo system on credit. The purchase agreement was: no down payment, an

interest rate of 18% per year (and hence 1.5% per month) and monthly payments of

$50.

The monthly payment is used to pay the interest due for that month and whatever is

left after that is used to pay part of the remaining debt.

Hence the first month you pay 1.5% of $1000 in interest - that is $15. So the

remaining $35 is deducted from the debt, leaving a debt of $965. The next month

you pay interest of 15% on the remaining $965, and etc. (The last payment may be

less than $50.)

Your program should determine the interest and principle paid each month, and the

total interest paid over the course of the loan, and output that information along with

the duration of the payments.