1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include <iostream>
#include <math.h>
#include "Function1d.h"
#include "csc350Lib_calculus_snle.h"
using namespace std;
using namespace csc350Lib_calc_base;
using namespace csc350Lib_calculus_snle;
//---------------------------------------------------------------
class MyFunc1 : public Function1D {
public:
float func(float);
bool isExactDerivativeDefined(void);
};
float MyFunc1::func(float x)
{
return cos(x+5);
}
bool MyFunc1::isExactDerivativeDefined(void)
{
return false;
}
//---------------------------------------------------------------
class PolyFunction1D : public Function1D{
public:
float func(float);
float dfunc(float);
bool isExactDerivativeDefined(void);
PolyFunction1D(int nbCoeffs, const float * coefficients)
{
numberOfCoeffs = nbCoeffs;
for (int i =0; i < nbCoeffs; i++) {
coeff[i] = *(coefficients + i);
}
};
private:
int numberOfCoeffs;
float coeff[5];
};
bool PolyFunction1D::isExactDerivativeDefined(void)
{
return true;
}
float PolyFunction1D::func(float x)
{
switch (numberOfCoeffs) {
case 0:
return 0;
break;
case 1:
return coeff[0];
break;
case 2:
return coeff[0] + coeff[1] * x;
break;
case 3:
return coeff[0] + (coeff[1] * x) + (coeff[2] * pow(x, 2));
break;
case 4:
return coeff[0] + (coeff[1] * x) + (coeff[2] * pow(x, 2)) + (coeff[3] * pow(x, 3));
break;
case 5:
return coeff[0] + (coeff[1] * x) + (coeff[2] * pow(x, 2)) + (coeff[3] * pow(x, 3)) + (coeff[4] * pow(x, 4));
break;
default:
return 0;
break;
}
}
float PolyFunction1D::dfunc(float x)
{
return (func(x)-func(x-.5))/(x - (x-.5));
}
//-----------------------------------------------------------------
int main (int argc, char * const argv[]) {
Function1D *f1, *f2;
f1 = new MyFunc1();
float numbers[]= {1,2,3,4,5}; // The coefficients of Polyfunction1D
f2 = new PolyFunction1D(5, numbers);
NonlinearSolver *nls;
nls = new NonlinearSolver_bisection();
nls->nleSolution = nls->solve(f1, 1., 4., 0.01);
float x = 3.f;
float y1 = f1->func(x),
y2 = f2->func(x),
dy1 = f1->dfunc(x),
dy2 = f2->dfunc(x);
cout << "Y1 = "<< y1 << endl;
cout << "Y2 = "<< y2 << endl;
cout << "Dy1 = " << dy1 << endl;
cout << "Dy2 = " << dy2 << endl;
cout << nls->nleSolution->getSolution() << " - Bisection x " <<endl;
cout << nls->nleSolution->getValueAtSolution() << " - Value of function at X" << endl;
cout << nls->nleSolution->getNumberOfIterations() << " - Number of iterations " << endl;
return 0;
}
|