Polynomial regression: Difference between revisions

m
<lang>
(<code>)
m (<lang>)
Line 14:
 
=={{header|Ada}}==
<codelang ada>
with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
 
Line 27:
return Solve (A * Transpose (A), A * Y);
end Fit;
</codelang>
The function Fit implements least squares approximation of a function defined in the points as specified by the arrays ''x''<sub>''i''</sub> and ''y''<sub>''i''</sub>. The basis &phi;<sub>''j''</sub> is ''x''<sup>''j''</sup>, ''j''=0,1,..,''N''. The implementation is straightforward. First the plane matrix A is created. A<sub>ji</sub>=&phi;<sub>''j''</sub>(''x''<sub>''i''</sub>). Then the linear problem AA<sup>''T''</sup>''c''=A''y'' is solved. The result ''c''<sub>''j''</sub> are the coefficients. Constraint_Error is propagated when dimensions of X and Y differ or else when the problem is ill-defined.
===Example===
<codelang ada>
with Fit;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
Line 46:
Put (C (2), Aft => 3, Exp => 0);
end Fitting;
</codelang>
Sample output:
<pre>
Line 54:
=={{header|Fortran}}==
{{libheader|LAPACK}}
<codelang fortran>
module fitting
contains
Line 119:
end module
</codelang>
 
===Example===
<codelang fortran>
program PolynomalFitting
use fitting
Line 142:
 
end program
</codelang>
 
Output (lower powers first, so this seems the opposite of the Python output):
Line 155:
 
{{libheader|numpy}}
<codelang python>
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
Line 161:
>>> coeffs
array([ 3., 2., 1.])
</codelang>
Substitute back received coefficients.
<codelang python>
>>> yf = numpy.polyval(numpy.poly1d(coeffs), x)
>>> yf
array([ 1., 6., 17., 34., 57., 86., 121., 162., 209., 262., 321.])
</codelang>
Find max absolute error.
<codelang python>
>>> '%.1g' % max(y-yf)
'1e-013'
</codelang>
 
===Example===
For input arrays `x' and `y':
<codelang python>
>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
</codelang>
 
<codelang python>
>>> p = numpy.poly1d(numpy.polyfit(x, y, deg=2), variable='N')
>>> print p
2
1.085 N + 10.36 N - 0.6164
</codelang>
Thus we confirm once more that for already sorted sequences the considered quick sort implementation has quadratic dependence on sequence length (see [[Query Performance|'''Example''' section for Python language on ''Query Performance'' page]]).
973

edits