c workshop #4

27
1 C workshop #4 Casting, Libraries, Financial Applications By: Yuli Kaplunovsky, [email protected], (408) 309 4506

Upload: catrin

Post on 25-Feb-2016

46 views

Category:

Documents


0 download

DESCRIPTION

C workshop #4. Casting, Libraries, Financial Applications By: Yuli Kaplunovsky, [email protected], (408) 309 4506. #define. #include #define PI 3.1415 #define ADD_ONE(X) (X+1) void main() { double D,F; int I,J; D = PI; F = ADD_ONE(D); I = 10; - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: C workshop #4

1

C workshop #4

Casting, Libraries, Financial Applications

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

Page 2: C workshop #4

2

#define#include <stdio.h>

#define PI 3.1415#define ADD_ONE(X) (X+1)

void main(){ double D,F; int I,J; D = PI; F = ADD_ONE(D);

I = 10; J = ADD_ONE(I);

printf("%g %g %d %d\n", D, F, I, J );}

Output:3.1415 4.1415 10 11

Page 3: C workshop #4

3

Inline comparing#include <stdio.h>#include <string.h>

void main(){ int I = 10, K; char ST[250];

K = (I > 4) ? 99:77; strcpy( ST, (I < 20)? "Less than 20" : "Above or Equal 20" );

printf("%d %d\n" "%s\n", I, K, ST );}

Output:10 99Less than 20

Page 4: C workshop #4

4

Pointers - sample #3 revised#include <stdio.h>

typedef struct { int X,Y,Z;} cord_struct;

int MyFunc( cord_struct *P ){ return P->X + P->Y;}

void main(){ int J,K,L; cord_struct Cord[10]; for ( J = 0 ; J < 10 ; J++ ) { Cord[J].X = J*2; Cord[J].Y = J*3 + 1; }

K = MyFunc( &Cord[0] ); L = MyFunc( &Cord[1] ); printf("%d,%d\n", K,L);}

Page 5: C workshop #4

5

Unsigned#include <stdio.h>void main(){ unsigned int U; U = 10; printf("%u\n", U);}

Output:10

Page 6: C workshop #4

6

Casting#include <stdio.h>void main(){ int J; unsigned int U; J = -33; U = J; if ( J == U ) printf("Equal \n"); if ( J < U ) printf("J is smaller\n"); printf("%d,%u\n", J, U);}

--------------------Configuration: CW - Win32 Debug--------------------Compiling...CW.cppe:\univ\berkeley\etc\c\cw\cw.cpp(8) : warning C4018: '==' : signed/unsigned mismatche:\univ\berkeley\etc\c\cw\cw.cpp(10) : warning C4018: '<' : signed/unsigned mismatchLinking...

CW.exe - 0 error(s), 2 warning(s)

Output:Equal-33,4294967263

Page 7: C workshop #4

7

Unsigned - remove warningsvoid main(){ int J; unsigned int U; J = -33; U = J; if ( J == (int)U ) printf("Equal \n"); if ( J < (int)U ) printf("J is smaller\n"); printf("%d,%u\n", J, U);}

--------------------Configuration: CW - Win32 Debug--------------------Compiling...CW.cppLinking...

CW.exe - 0 error(s), 0 warning(s)

Output:Equal-33,4294967263

Page 8: C workshop #4

8

void pointer#include <stdio.h>void main(){ int I, J; void *P; I = 20; P = &I; J = *P; printf("%d\n", J);}

--------------------Configuration: CW - Win32 Debug--------------------Compiling...CW.cppe:\univ\berkeley\etc\c\cw\cw.cpp(8) : error C2100: illegal indirectione:\univ\berkeley\etc\c\cw\cw.cpp(8) : error C2440: '=' : cannot convert from 'void *' to 'int' This conversion requires a reinterpret_cast, a C-style cast or function-style castError executing cl.exe.

CW.exe - 2 error(s), 0 warning(s)

Page 9: C workshop #4

9

Casting void pointers#include <stdio.h>void main(){ int I, J; void *P; I = 20; P = &I; J = *(int *)P; printf("%d\n", J);}

Output:20

Page 10: C workshop #4

10

sizeof#include <stdio.h>

void main(){ int I; char C; double D; float F; char ST[10];

printf("%d %d %d %d %d\n", sizeof(I), sizeof(C), sizeof(D), sizeof(F), sizeof(ST) );

}

Output:4 1 8 4 10

Page 11: C workshop #4

11

memcpy#include <stdio.h>#include <memory.h>

void main(){ int A1[7] = { 33, 44, 55, 1, -10, 90, 7}; int A2[7];

memcpy( A1, A2, sizeof(A1) );

printf("%d\n", sizeof(A1) );} Output:

28

Page 12: C workshop #4

12

void / int casting#include <stdio.h>

void MyMemcpy( void *Src, void *Dst, int Len ){ int I; unsigned char C; for ( I = 0 ; I < Len ; I++ ) { C = *(unsigned char *)Src; *(unsigned char *)Dst = C; Src = (void *) ((int)Src + 1); Dst = (void *) ((int)Dst + 1); }}

void main(){ int A1[7] = { 33, 44, 55, 1, -10, 90, 7}; int A2[7], K;

printf("%d\n", sizeof(A1) );

MyMemcpy( A1, A2, sizeof(A1) );

for ( K = 0 ; K < 7 ; K++ ) printf("%d,",A1[K] ); printf("\n");

for ( K = 0 ; K < 7 ; K++ ) printf("%d,",A2[K] ); printf("\n");}

Output:2833,44,55,1,-10,90,7,33,44,55,1,-10,90,7,

Page 13: C workshop #4

13

long / short#include <stdio.h>

void main(){ long int L; short int S; int I; long double LD; double D;

printf("%d %d %d\n", sizeof(L), sizeof(S), sizeof(I) ); printf("%d %d\n", sizeof(LD), sizeof(D) );

}

Output:4 2 48 8

Page 14: C workshop #4

14

Standard libraries - math.h/* ABS.C: This program computes and displays * the absolute values of several numbers. */

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

void main( void ){ int ix = -4, iy; long lx = -41567L, ly; double dx = -3.141593, dy;

iy = abs( ix ); printf( "The absolute value of %d is %d\n", ix, iy);

ly = labs( lx ); printf( "The absolute value of %ld is %ld\n", lx, ly);

dy = fabs( dx ); printf( "The absolute value of %f is %f\n", dx, dy );}

Output:The absolute value of -4 is 4The absolute value of -41567 is 41567The absolute value of -3.141593 is 3.141593

Page 15: C workshop #4

15

Math.hint abs(int);double acos(double);double asin(double);double atan(double);double atan2(double, double);double cos(double);double cosh(double);double exp(double);double fabs(double);double fmod(double, double);long labs(long);double log(double);double log10(double);double pow(double, double);double sin(double);double sinh(double);double tan(double);double tanh(double);double sqrt(double);double atof(const char *);double ceil(double);double floor(double);

Page 16: C workshop #4

16

Stdlib.hvoid srand(unsigned int);

int rand(void);

char * itoa(int, char *, int);

double atof(const char *);

int atoi(const char *);

Page 17: C workshop #4

17

Function prototype// *********************************************************// Program Name : Test33.cpp// Does : A sample program to show Add function// Written By : Yuli Kaplunovsky, 6/12/2002// Last modified:// // Remarks : // *********************************************************

// *********************************************************// Includes// *********************************************************#include <stdio.h>

// *********************************************************// Prototypes// *********************************************************int MyFunc( int A, int B );

// *********************************************************// Function: main()// *********************************************************void main(){ int I; I = MyFunc( 10, 20 ); printf("%d\n", I );}

// *********************************************************// Function: MyFunc()// Does : Adds two numbers// Input : Two integer numbers// Output : The addition results as an integer// *********************************************************int MyFunc( int A, int B ){ return A + B;}

Output:30

Page 18: C workshop #4

18

Page 19: C workshop #4

19

Our own .h fileFile MyFuncs.h

int MyFunc( int, int );

File cw.cpp

#include <stdio.h>#include "MyFuncs.h"

void main(){ int I; I = MyFunc( 10, 20 ); printf("%d\n", I );}

File MyFuncs.cpp

#include "MyFuncs.h"

int MyFunc( int A, int B ){ return A + B;}

Page 20: C workshop #4

20

Financial applications - Normal Distribution

// ****************************************************// ****************************************************double N_func( double X ) // The cumulative normal distribution{ double L, K, w ;

double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937; double const a4 = -1.821255978, a5 = 1.330274429;

L = fabs(X); K = 1.0 / (1.0 + 0.2316419 * L); w = 1.0 - 1.0 / sqrt(2 * Pi) * exp(-L *L / 2) * (a1 * K + a2 * K *K + a3 *

pow(K,3) + a4 * pow(K,4) + a5 * pow(K,5));

if (X < 0 ) w= 1.0 - w;

return w;}

Page 21: C workshop #4

21

Black Scholes (there is a mistake)

// ****************************************************// ****************************************************double BS( double S, double K, double Sig, double t, double r ){ double d1, d2; double t_sqrt = sqrt(t); d1 = (log(S/K) * r * t) / (Sig * t_sqrt ) + 0.5 * Sig * t_sqrt; d2 = d1 - (Sig*t_sqrt); return S * N_func(d1) - K * exp( -r * t ) * N_func(d2);}

Page 22: C workshop #4

22

‘Numerical Recipes in C’• By: Press, Teukolsky, Vetterling./* Driver for routine fit */#include <stdio.h>#define NRANSI#include "nr.h"#include "nrutil.h"

#define NPT 100#define SPREAD 0.5

int main(void){

long idum=(-117);int i,mwt;float a,b,chi2,q,siga,sigb,*x,*y,*sig;

x=vector(1,NPT);y=vector(1,NPT);sig=vector(1,NPT);for (i=1;i<=NPT;i++) {x[i]=0.1*i;y[i] = -2.0*x[i]+1.0+SPREAD*gasdev(&idum);sig[i]=SPREAD;}for (mwt=0;mwt<=1;mwt++) {fit(x,y,NPT,sig,mwt,&a,&b,&siga,&sigb,&chi2,&q);if (mwt == 0) printf("\nIgnoring standard deviations\n");else printf("\nIncluding standard deviations\n");printf("%12s %9.6f %18s %9.6f \n", "a = ",a,"uncertainty:",siga);printf("%12s %9.6f %18s %9.6f \n", "b = ",b,"uncertainty:",sigb);printf("%19s %14.6f \n","chi-squared: ",chi2);printf("%23s %10.6f \n","goodness-of-fit: ",q);}free_vector(sig,1,NPT);free_vector(y,1,NPT);free_vector(x,1,NPT);return 0;

}#undef NRANSI

Output:Ignoring standard deviations a = 1.079574 uncertainty: 0.099821 b = -2.006663 uncertainty: 0.017161 chi-squared: 24.047945 goodness-of-fit: 1.000000

Including standard deviations a = 1.079574 uncertainty: 0.100755 b = -2.006663 uncertainty: 0.017321 chi-squared: 96.191780 goodness-of-fit: 0.532773

Page 23: C workshop #4

23

#include <math.h>#define NRANSI#include "nrutil.h"

void fit(float x[], float y[], int ndata, float sig[], int mwt, float *a,float *b, float *siga, float *sigb, float *chi2, float *q)

{float gammq(float a, float x);int i;float wt,t,sxoss,sx=0.0,sy=0.0,st2=0.0,ss,sigdat;

*b=0.0;if (mwt) {ss=0.0;for (i=1;i<=ndata;i++) {wt=1.0/SQR(sig[i]);ss += wt;sx += x[i]*wt;sy += y[i]*wt;}} else {for (i=1;i<=ndata;i++) {sx += x[i];sy += y[i];}ss=ndata;}sxoss=sx/ss;if (mwt) {for (i=1;i<=ndata;i++) {t=(x[i]-sxoss)/sig[i];st2 += t*t;*b += t*y[i]/sig[i];}} else {for (i=1;i<=ndata;i++) {t=x[i]-sxoss;st2 += t*t;*b += t*y[i];}}*b /= st2;*a=(sy-sx*(*b))/ss;*siga=sqrt((1.0+sx*sx/(ss*st2))/ss);*sigb=sqrt(1.0/st2);*chi2=0.0;*q=1.0;if (mwt == 0) {for (i=1;i<=ndata;i++)*chi2 += SQR(y[i]-(*a)-(*b)*x[i]);sigdat=sqrt((*chi2)/(ndata-2));*siga *= sigdat;*sigb *= sigdat;} else {for (i=1;i<=ndata;i++)*chi2 += SQR((y[i]-(*a)-(*b)*x[i])/sig[i]);if (ndata>2) *q=gammq(0.5*(ndata-2),0.5*(*chi2));}

}#undef NRANSI

Page 24: C workshop #4

24

Page 25: C workshop #4

25

Operator Precedence Highest Precedence ++ Post-increment (Left to right)-- Post-decrement ( ) Function call [ ] Array element -> Pointer to structure member . Structure or union member ++ Pre-increment (Right to left)-- Pre-decrement ! Logical NOT ~ Bitwise NOT - Unary minus + Unary plus & Address * Indirection sizeof Size in bytes new Allocate program memory delete Deallocate program memory (type) Type cast [for example, (float) i] .* Pointer to member (objects) (Left to right) ->* Pointer to member (pointers) * Multiply (Left to right) / Divide % Remainder + Add (Left to right) - Subtract << Left shift (Left to right) >> Right shift < Less than (Left to right) <= Less than or equal to > Greater than >= Greater than or equal to == Equal (Left to right) != Not equal & Bitwise AND (Left to right) ^ Bitwise exclusive OR (Left to right) | Bitwise OR (Left to right) && Logical AND (Left to right) || Logical OR (Left to right) ? : Conditional (Right to left) = Assignment (Right to left) *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |= Compound assignment , Comma (Left to right)

Page 26: C workshop #4

26

Quiz1. Write a program that finds intercept of a given function with 0 using

the Newton-Raphson method.

The function Y = F(X) is defined as:double Func( double X );

Page 27: C workshop #4

27

Next• Saturday

C/C++Interface to excelGraphs???More financial applications Question session