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
|
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
inline bool findQuadCoefficients(double timeArray[], double valueArray[],double &a, double &b, double &critPoint, int PointsNum){
//return false if error
//a and b are not calculated now
// cout << "Entering findQuadCoefficients:" << endl;
const double S00=PointsNum;//points number
double S40=0, S10=0, S20=0, S30=0, S01=0, S11=0, S21 = 0;
double value = 0, indexPow2 = 0;
const double MINvalue = valueArray[0];
const double MINtime = timeArray[0];
int index = -1;
for (int i=0; i<PointsNum; i++ ){
index = timeArray[i] - MINtime;
value = (valueArray[i] - MINvalue); //normalizing
// cout << "i=" << i << " index=" << index << " value=" << value << endl;
S40+= pow(index,4);
S30+= pow(index,3);
indexPow2 = pow(index,2);
S20+= indexPow2;
S10+= index;
S01 += value;
S11 += value*index;
S21 += value*indexPow2;
}
double S20squared = pow(S20,2);
//minors M_ij=M_ji
double M11 = S20*S00;
M11 -= pow(S10,2);
double M21 = S30*S00;
M21 -= S20*S10;
double M22 = S40*S00;
M22 -= S20squared;
double M31 = S30*S10;
M31 -= S20squared;
double M32 = S40*S10;
M32 -= S20*S30;
// double M33 = S40*S20 - pow(S30,2);
double discriminant = S40*M11;
discriminant -= S30*M21;
discriminant += S20*M31;
// cout << "discriminant=" << discriminant << endl;
if (abs(discriminant) < .00000000001) return false;
double Da = S21*M11;
Da -= S11*M21;
Da += S01*M31;
a = Da/discriminant;
// cout << "discriminant=" << discriminant;
// cout << " Da=" << Da;
double Db = -S21*M21;
Db += S11*M22;
Db -= S01*M32;
b = Db/discriminant;
// cout << " Db=" << Db << endl;
critPoint = -Db/(2*Da) + MINtime; //-b/(2*a)= -Db/discriminant / (2*(Da/discriminant)) = -Db/(2*Da);
return true;
};
//test
int main (int argc, char *argv[])
{
double timeArray[9] = {10., 11., 12., 13., 14., 15., 16., 17., 18.};
double valueArray[9];
double a=13., b=-1., c=4.;
double a2=0, b2=0, c2=0;
double critPoint = 0;
for (unsigned int i=0; i<9; i++ ){
valueArray[i] = a*timeArray[i]*timeArray[i] +b*timeArray[i] + c;
}
bool success = findQuadCoefficients(timeArray, valueArray, a2, b2, critPoint, 44);
cout << "success =" << success << " a2=" << a2 << " b2=" << b2 << endl;
}
|