Curve Fitting y = ab^x Using C++ with Output
C++ Program for fitting curve y=abx using least square method with output.
C++ Program for Fitting y = abx
#include<iostream>
#include<math.h>
#define S 50
using namespace std;
int main()
{
int n, i;
float x[S], y[S], sumX=0, sumX2=0, sumY=0, sumXY=0, a, b, A, B;
/* Input */
cout<<"How many data points? " << endl;
cin >> n;
for(i=1;i<=n;i++)
{
cout << "x["<< i <<"] = ";
cin >> x[i];
cout << "y["<< i <<"] = ";
cin >> y[i];
}
/* Calculating Required Sum */
for(i=1;i<=n;i++)
{
sumX = sumX + x[i];
sumX2 = sumX2 + x[i]*x[i];
sumY = sumY + log(y[i]);
sumXY = sumXY + x[i]*log(y[i]);
}
/* Calculating A and B */
B = (n*sumXY-sumX*sumY)/(n*sumX2-sumX*sumX);
A = (sumY - B*sumX)/n;
/* Transformation of A to a and B to b */
a = exp(A);
b = exp(B);
/* Displaying value of a and b */
cout << "Values are: a = " << a << " and b = " << b;
return(0);
}
Output
How many data points? 5 x[1] = 0 y[1] = 3 x[2] = 1 y[2] = 6 x[3] = 2 y[3] = 12 x[4] = 3 y[4] = 24 x[5] = 4 y[5] = 48 Values are: a = 3 and b = 2
Recommended Readings