Discrete
Approximates a discrete function using least squares polynomial fitting.
You're viewing an older version of this page (#89). View the current version.
Interface
#include <codecogs/maths/approximation/regression/discrete.h>
using namespace Maths::Approximation::Regression;
Overview
This class approximates an arbitrary discrete function using polynomial least squares fitting.
The algorithm finds the coefficients , with
such that the following polynomial fits the given set of points with minimum error, in terms of leasts squares minimization
An important detail when using this class is that the abscissas array given as argument to the constructor needs to be sorted in ascending order and its elements need to be equally spaced, meaning that:
where N is the size of the array. In other words, the associated function needs to be discrete.
Below you will find the regression graph for a set of points obtained by evaluating the function , displayed in light blue, at particular abscissas. The regression polynomial, displayed in red, has been calculated using this class. The root mean squared error is also displayed.

References
- Jean-Pierre Moreau's Home Page, http://perso.wanadoo.fr/jean-pierre.moreau/
- Claude Nowakowski, "Méthodes de calcul numérique", Tome 2, PSI Edition, 1984
Example 1
The following example displays 10 approximated values (you may change this amount through the N_out variable) for the function with abscissas equally spaced in the
interval. The X and Y coordinate arrays are initialized by evaluating this function for N = 12 points equally spaced in the domain from
to
.
#include <codecogs/maths/regression/discrete.h>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
#define PI 3.1415926535897932384626433832795
#define N 12
int main()
{
// Declare and initialize two arrays to hold the coordinates of the initial data points
double x[N], y[N];
// Generate the points
double xx = PI, step = 4 * PI / (N - 1);
for (int i = 0; i < N; ++i, xx += step) {
x[i] = xx;
y[i] = sin(xx) + xx;
}
// Initialize the regression approximation routine with known data points
Maths::Regression::Discrete A(N, x, y, 7);
// Interrogate the regression function to find approximated values
int N_out = 10;
xx = PI, step = (3 * PI) / (N_out - 1);
for (int i = 0; i < N_out; ++i, xx += step) {
cout << "x = " << setw(7) << xx << " y = ";
cout << setw(11) << A.getValue(xx) << endl;
}
return 0;
}Output:
x = 3.14159 y = 2.81243
x = 4.18879 y = 3.91449
x = 5.23599 y = 5.01655
x = 6.28319 y = 6.11861
x = 7.33038 y = 7.22066
x = 8.37758 y = 8.32272
x = 9.42478 y = 9.42478
x = 10.472 y = 10.5268
x = 11.5192 y = 11.6289
x = 12.5664 y = 12.731Members of Discrete
CLASS METHOD
Discrete
Initializes the necessary data for following evaluations of the polynomial.
CLASS METHOD
Discrete
Class destructor
CLASS METHOD
getValue
Returns the approximated ordinate at the given abscissa.
Parameters
CLASS METHOD