Polynomial regression: Difference between revisions

 
(64 intermediate revisions by 34 users not shown)
Line 12:
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
 
=={{header|11l}}==
{{trans|Swift}}
 
<syntaxhighlight lang="11l">F average(arr)
R sum(arr) / Float(arr.len)
 
F poly_regression(x, y)
V xm = average(x)
V ym = average(y)
V x2m = average(x.map(i -> i * i))
V x3m = average(x.map(i -> i ^ 3))
V x4m = average(x.map(i -> i ^ 4))
V xym = average(zip(x, y).map((i, j) -> i * j))
V x2ym = average(zip(x, y).map((i, j) -> i * i * j))
V sxx = x2m - xm * xm
V sxy = xym - xm * ym
V sxx2 = x3m - xm * x2m
V sx2x2 = x4m - x2m * x2m
V sx2y = x2ym - x2m * ym
V b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
V c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
V a = ym - b * xm - c * x2m
 
F abc(xx)
R (@a + @b * xx) + (@c * xx * xx)
 
print("y = #. + #.x + #.x^2\n".format(a, b, c))
print(‘ Input Approximation’)
print(‘ x y y1’)
 
L(i) 0 .< x.len
print(‘#2 #3 #3.1’.format(x[i], y[i], abc(i)))
 
V x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
V y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
poly_regression(x, y)</syntaxhighlight>
 
{{out}}
<pre>
y = 1 + 2x + 3x^2
 
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;
 
function Fit (X, Y : Real_Vector; N : Positive) return Real_Vector is
Line 25 ⟶ 80:
end loop;
return Solve (A * Transpose (A), A * Y);
end Fit;</langsyntaxhighlight>
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===
<langsyntaxhighlight lang="ada">with Fit;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
 
Line 42 ⟶ 97:
Put (C (1), Aft => 3, Exp => 0);
Put (C (2), Aft => 3, Exp => 0);
end Fitting;</langsyntaxhighlight>
{{out}}
<pre>
Line 55 ⟶ 110:
 
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386 - ELLA has no FORMATted transput}} -->
<langsyntaxhighlight lang="algol68">MODE FIELD = REAL;
 
MODE
Line 168 ⟶ 223:
);
print polynomial(d)
END # fitting #</langsyntaxhighlight>
{{out}}
<pre>
3x**2+2x+1
1.0848x**2+10.3552x-0.6164
</pre>
 
=={{header|AutoHotkey}}==
{{trans|Lua}}
<syntaxhighlight lang="autohotkey">
regression(xa,ya){
n := xa.Count()
xm := ym := x2m := x3m := x4m := xym := x2ym := 0
loop % n {
i := A_Index
xm := xm + xa[i]
ym := ym + ya[i]
x2m := x2m + xa[i] * xa[i]
x3m := x3m + xa[i] * xa[i] * xa[i]
x4m := x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym := xym + xa[i] * ya[i]
x2ym := x2ym + xa[i] * xa[i] * ya[i]
}
xm := xm / n
ym := ym / n
x2m := x2m / n
x3m := x3m / n
x4m := x4m / n
xym := xym / n
x2ym := x2ym / n
 
sxx := x2m - xm * xm
sxy := xym - xm * ym
sxx2 := x3m - xm * x2m
sx2x2 := x4m - x2m * x2m
sx2y := x2ym - x2m * ym
 
b := (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
c := (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
a := ym - b * xm - c * x2m
result := "Input`tApproximation`nx y`ty1`n"
loop % n
i := A_Index, result .= xa[i] ", " ya[i] "`t" eval(a, b, c, xa[i]) "`n"
return "y = " c "x^2" " + " b "x + " a "`n`n" result
}
eval(a,b,c,x){
return a + (b + c*x) * x
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">xa := [0, 1, 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10]
ya := [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
MsgBox % result := regression(xa, ya)
return</syntaxhighlight>
{{out}}
<pre>y = 3.000000x^2 + 2.000000x + 1.000000
 
Input Approximation
x y y1
0, 1 1.000000
1, 6 6.000000
2, 17 17.000000
3, 34 34.000000
4, 57 57.000000
5, 86 86.000000
6, 121 121.000000
7, 162 162.000000
8, 209 209.000000
9, 262 262.000000
10, 321 321.000000</pre>
 
=={{header|AWK}}==
{{trans|Lua}}
<syntaxhighlight lang="awk">
BEGIN{
i = 0;
xa[i] = 0; i++;
xa[i] = 1; i++;
xa[i] = 2; i++;
xa[i] = 3; i++;
xa[i] = 4; i++;
xa[i] = 5; i++;
xa[i] = 6; i++;
xa[i] = 7; i++;
xa[i] = 8; i++;
xa[i] = 9; i++;
xa[i] = 10; i++;
i = 0;
ya[i] = 1; i++;
ya[i] = 6; i++;
ya[i] = 17; i++;
ya[i] = 34; i++;
ya[i] = 57; i++;
ya[i] = 86; i++;
ya[i] =121; i++;
ya[i] =162; i++;
ya[i] =209; i++;
ya[i] =262; i++;
ya[i] =321; i++;
exit;
}
{
# (nothing to do)
}
END{
a = 0; b = 0; c = 0; # globals - will change by regression()
regression(xa,ya);
 
printf("y = %6.2f x^2 + %6.2f x + %6.2f\n",c,b,a);
printf("%-13s %-8s\n","Input","Approximation");
printf("%-6s %-6s %-8s\n","x","y","y^")
for (i=0;i<length(xa);i++) {
printf("%6.1f %6.1f %8.3f\n",xa[i],ya[i],eval(a,b,c,xa[i]));
}
}
 
function eval(a,b,c,x) {
return a+b*x+c*x*x;
}
# locals
function regression(x,y, n,xm,ym,x2m,x3m,x4m,xym,x2ym,sxx,sxy,sxx2,sx2x2,sx2y) {
n = 0
xm = 0.0;
ym = 0.0;
x2m = 0.0;
x3m = 0.0;
x4m = 0.0;
xym = 0.0;
x2ym = 0.0;
 
for (i in x) {
xm += x[i];
ym += y[i];
x2m += x[i] * x[i];
x3m += x[i] * x[i] * x[i];
x4m += x[i] * x[i] * x[i] * x[i];
xym += x[i] * y[i];
x2ym += x[i] * x[i] * y[i];
n++;
}
xm = xm / n;
ym = ym / n;
x2m = x2m / n;
x3m = x3m / n;
x4m = x4m / n;
xym = xym / n;
x2ym = x2ym / n;
 
sxx = x2m - xm * xm;
sxy = xym - xm * ym;
sxx2 = x3m - xm * x2m;
sx2x2 = x4m - x2m * x2m;
sx2y = x2ym - x2m * ym;
 
b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
a = ym - b * xm - c * x2m;
}
</syntaxhighlight>
{{out}}
<pre>
y = 3.00 x^2 + 2.00 x + 1.00
Input Approximation
x y y^
0.0 1.0 1.000
1.0 6.0 6.000
2.0 17.0 17.000
3.0 34.0 34.000
4.0 57.0 57.000
5.0 86.0 86.000
6.0 121.0 121.000
7.0 162.0 162.000
8.0 209.0 209.000
9.0 262.0 262.000
10.0 321.0 321.000
</pre>
 
Line 180 ⟶ 406:
and fits an order-5 polynomial, so the test data for this task
is hardly challenging!
<langsyntaxhighlight lang="bbcbasic"> INSTALL @lib$+"ARRAYLIB"
Max% = 10000
Line 228 ⟶ 454:
FOR term% = 5 TO 0 STEP -1
PRINT ;vector(term%) " * x^" STR$(term%)
NEXT</langsyntaxhighlight>
{{out}}
<pre>
Line 244 ⟶ 470:
 
'''Include''' file (to make the code reusable easily) named <tt>polifitgsl.h</tt>
<langsyntaxhighlight lang="c">#ifndef _POLIFITGSL_H
#define _POLIFITGSL_H
#include <gsl/gsl_multifit.h>
Line 251 ⟶ 477:
bool polynomialfit(int obs, int degree,
double *dx, double *dy, double *store); /* n, p */
#endif</langsyntaxhighlight>
'''Implementation''' (the examples [http://www.gnu.org/software/gsl/manual/html_node/Fitting-Examples.html here] helped alot to code this quickly):
<langsyntaxhighlight lang="c">#include "polifitgsl.h"
 
bool polynomialfit(int obs, int degree,
Line 293 ⟶ 519:
return true; /* we do not "analyse" the result (cov matrix mainly)
to know if the fit is "good" */
}</langsyntaxhighlight>
'''Testing''':
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#include "polifitgsl.h"
Line 315 ⟶ 541:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>1.000000
Line 321 ⟶ 547:
3.000000</pre>
 
=={{header|CommonC Lispsharp|C#}}==
 
Uses the routine (lsqr A b) from [[Multiple regression]] and (mtp A) from [[Matrix transposition]].
 
<lang lisp>;; Least square fit of a polynomial of order n the x-y-curve.
(defun polyfit (x y n)
(let* ((m (cadr (array-dimensions x)))
(A (make-array `(,m ,(+ n 1)) :initial-element 0)))
(loop for i from 0 to (- m 1) do
(loop for j from 0 to n do
(setf (aref A i j)
(expt (aref x 0 i) j))))
(lsqr A (mtp y))))</lang>
 
Example:
 
<lang lisp>(let ((x (make-array '(1 11) :initial-contents '((0 1 2 3 4 5 6 7 8 9 10))))
(y (make-array '(1 11) :initial-contents '((1 6 17 34 57 86 121 162 209 262 321)))))
(polyfit x y 2))
 
#2A((0.9999999999999759d0) (2.000000000000005d0) (3.0d0))</lang>
 
=={{header|C sharp}}==
 
{{libheader|Math.Net}}
<syntaxhighlight lang="csharp"> public static double[] Polyfit(double[] x, double[] y, int degree)
 
<lang C sharp> public static double[] Polyfit(double[] x, double[] y, int degree)
{
// Vandermonde matrix
Line 354 ⟶ 556:
for (int j = 0; j <= degree; j++) v[i, j] = Math.Pow(x[i], j);
var yv = new DenseVector(y).ToColumnMatrix();
QR<double> qr = v.QR();
// Math.Net doesn't have an "economy" QR, so:
// cut R short to square upper triangle, then recompute Q
Line 361 ⟶ 563:
var p = r.Inverse().Multiply(q.TransposeThisAndMultiply(yv));
return p.Column(0).ToArray();
}</langsyntaxhighlight>
Example:
<langsyntaxhighlight Clang="c sharp"> static void Main(string[] args)
{
const int degree = 2;
Line 372 ⟶ 574:
Console.WriteLine();
for (int i = 0; i < x.Length; i++ )
Console.WriteLine("{0} => {1} diff {2}", x[i], PolyvalPolynomial.Evaluate(p,x[i], p), y[i] - PolyvalPolynomial.Evaluate(p,x[i], p));
Console.ReadKey(true);
}</langsyntaxhighlight>
 
=={{header|C++}}==
{{trans|Java}}
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
 
void polyRegression(const std::vector<int>& x, const std::vector<int>& y) {
int n = x.size();
std::vector<int> r(n);
std::iota(r.begin(), r.end(), 0);
double xm = std::accumulate(x.begin(), x.end(), 0.0) / x.size();
double ym = std::accumulate(y.begin(), y.end(), 0.0) / y.size();
double x2m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a; }) / r.size();
double x3m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a; }) / r.size();
double x4m = std::transform_reduce(r.begin(), r.end(), 0.0, std::plus<double>{}, [](double a) {return a * a * a * a; }) / r.size();
 
double xym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, std::multiplies<double>{});
xym /= fmin(x.size(), y.size());
 
double x2ym = std::transform_reduce(x.begin(), x.end(), y.begin(), 0.0, std::plus<double>{}, [](double a, double b) { return a * a * b; });
x2ym /= fmin(x.size(), y.size());
 
double sxx = x2m - xm * xm;
double sxy = xym - xm * ym;
double sxx2 = x3m - xm * x2m;
double sx2x2 = x4m - x2m * x2m;
double sx2y = x2ym - x2m * ym;
 
double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double a = ym - b * xm - c * x2m;
 
auto abc = [a, b, c](int xx) {
return a + b * xx + c * xx*xx;
};
 
std::cout << "y = " << a << " + " << b << "x + " << c << "x^2" << std::endl;
std::cout << " Input Approximation" << std::endl;
std::cout << " x y y1" << std::endl;
 
auto xit = x.cbegin();
auto xend = x.cend();
auto yit = y.cbegin();
auto yend = y.cend();
while (xit != xend && yit != yend) {
printf("%2d %3d %5.1f\n", *xit, *yit, abc(*xit));
xit = std::next(xit);
yit = std::next(yit);
}
}
 
int main() {
using namespace std;
 
vector<int> x(11);
iota(x.begin(), x.end(), 0);
 
vector<int> y{ 1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321 };
 
polyRegression(x, y);
 
return 0;
}</syntaxhighlight>
{{out}}
<pre>y = 1 + 2x + 3x^2
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0</pre>
 
=={{header|Common Lisp}}==
Uses the routine (lsqr A b) from [[Multiple regression]] and (mtp A) from [[Matrix transposition]].
 
<syntaxhighlight lang="lisp">;; Least square fit of a polynomial of order n the x-y-curve.
(defun polyfit (x y n)
(let* ((m (cadr (array-dimensions x)))
(A (make-array `(,m ,(+ n 1)) :initial-element 0)))
(loop for i from 0 to (- m 1) do
(loop for j from 0 to n do
(setf (aref A i j)
(expt (aref x 0 i) j))))
(lsqr A (mtp y))))</syntaxhighlight>
 
Example:
 
<syntaxhighlight lang="lisp">(let ((x (make-array '(1 11) :initial-contents '((0 1 2 3 4 5 6 7 8 9 10))))
(y (make-array '(1 11) :initial-contents '((1 6 17 34 57 86 121 162 209 262 321)))))
(polyfit x y 2))
 
#2A((0.9999999999999759d0) (2.000000000000005d0) (3.0d0))</syntaxhighlight>
 
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight Dlang="d">import std.algorithm;
import std.range;
import std.stdio;
Line 426 ⟶ 727:
auto y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
polyRegression(x, y);
}</langsyntaxhighlight>
{{out}}
<pre>y = 1 + 2x + 3x^2
Line 442 ⟶ 743:
9 262 262.0
10 321 321.0</pre>
 
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight lang=easylang>
func eval a b c x .
return a + (b + c * x) * x
.
proc regression xa[] ya[] . .
n = len xa[]
for i = 1 to n
xm = xm + xa[i]
ym = ym + ya[i]
x2m = x2m + xa[i] * xa[i]
x3m = x3m + xa[i] * xa[i] * xa[i]
x4m = x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym = xym + xa[i] * ya[i]
x2ym = x2ym + xa[i] * xa[i] * ya[i]
.
xm = xm / n
ym = ym / n
x2m = x2m / n
x3m = x3m / n
x4m = x4m / n
xym = xym / n
x2ym = x2ym / n
#
sxx = x2m - xm * xm
sxy = xym - xm * ym
sxx2 = x3m - xm * x2m
sx2x2 = x4m - x2m * x2m
sx2y = x2ym - x2m * ym
#
b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
a = ym - b * xm - c * x2m
print "y = " & a & " + " & b & "x + " & c & "x^2"
numfmt 0 3
for i = 1 to n
print xa[i] & " " & ya[i] & " " & eval a b c xa[i]
.
.
xa[] = [ 0 1 2 3 4 5 6 7 8 9 10 ]
ya[] = [ 1 6 17 34 57 86 121 162 209 262 321 ]
regression xa[] ya[]
</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
 
{{libheader|Calc}}
Simple solution by Emacs Lisp and built-in Emacs Calc.
<syntaxhighlight lang="lisp">(let ((x '(0 1 2 3 4 5 6 7 8 9 10))
(y '(1 6 17 34 57 86 121 162 209 262 321)))
(calc-eval "fit(a*x^2+b*x+c,[x],[a,b,c],[$1 $2])" nil (cons 'vec x) (cons 'vec y)))</syntaxhighlight>
 
{{out}}
<lang emacs-lisp>
(setq x '[0 1 2 3 4 5 6 7 8 9 10])
(setq y '[1 6 17 34 57 86 121 162 209 262 321])
(calc-eval
(format "fit(a*x^2+b*x+c,[x],[a,b,c],[%s %s])" x y))
</lang>
 
"3. x^2 + 1.99999999996 x + 1.00000000006"
{{out}}
<pre>
"3. x^2 + 1.99999999996 x + 1.00000000006"
</pre>
 
=={{header|Fortran}}==
{{libheader|LAPACK}}
<langsyntaxhighlight lang="fortran">module fitting
contains
 
Line 524 ⟶ 865:
end function
end module</langsyntaxhighlight>
 
===Example===
<langsyntaxhighlight lang="fortran">program PolynomalFitting
use fitting
implicit none
Line 545 ⟶ 886:
write (*, '(F9.4)') a
 
end program</langsyntaxhighlight>
 
{{out}} (lower powers first, so this seems the opposite of the Python output):
Line 555 ⟶ 896:
 
=={{header|FreeBASIC}}==
General regressions for different polynomials, here it is for degree 2, (3 terms).
<lang FreeBASIC>Sub GaussJordan(matrix() As Double,rhs() As Double,ans() As Double)
<syntaxhighlight lang="freebasic">#Include "crt.bi" 'for rounding only
Dim As Integer n=Ubound(matrix,1)
 
Redim ans(0):Redim ans(1 To n)
Type vector
Dim As Double b(1 To n,1 To n),r(1 To n)
Dim As Double element(Any)
For c As Integer=1 To n 'take copies
End Type
r(c)=rhs(c)
 
For d As Integer=1 To n
Type b(c,d)=matrix(c,d)
Dim As Double Next delement(Any,Any)
Declare Function inverse() As matrix
Next c
Declare Function transpose() As matrix
private:
Declare Function GaussJordan(As vector) As vector
End Type
 
'mult operators
Operator *(m1 As matrix,m2 As matrix) As matrix
Dim rows As Integer=Ubound(m1.element,1)
Dim columns As Integer=Ubound(m2.element,2)
If Ubound(m1.element,2)<>Ubound(m2.element,1) Then
Print "Can't do"
Exit Operator
End If
Dim As matrix ans
Redim ans.element(rows,columns)
Dim rxc As Double
For r As Integer=1 To rows
For c As Integer=1 To columns
rxc=0
For k As Integer = 1 To Ubound(m1.element,2)
rxc=rxc+m1.element(r,k)*m2.element(k,c)
Next k
ans.element(r,c)=rxc
Next c
Next r
Operator= ans
End Operator
 
Operator *(m1 As matrix,m2 As vector) As vector
Dim rows As Integer=Ubound(m1.element,1)
Dim columns As Integer=Ubound(m2.element,2)
If Ubound(m1.element,2)<>Ubound(m2.element) Then
Print "Can't do"
Exit Operator
End If
Dim As vector ans
Redim ans.element(rows)
Dim rxc As Double
For r As Integer=1 To rows
rxc=0
For k As Integer = 1 To Ubound(m1.element,2)
rxc=rxc+m1.element(r,k)*m2.element(k)
Next k
ans.element(r)=rxc
Next r
Operator= ans
End Operator
 
Function matrix.transpose() As matrix
Dim As matrix b
Redim b.element(1 To Ubound(this.element,2),1 To Ubound(this.element,1))
For i As Long=1 To Ubound(this.element,1)
For j As Long=1 To Ubound(this.element,2)
b.element(j,i)=this.element(i,j)
Next
Next
Return b
End Function
 
Function matrix.GaussJordan(rhs As vector) As vector
Dim As Integer n=Ubound(rhs.element)
Dim As vector ans=rhs,r=rhs
Dim As matrix b=This
#macro pivot(num)
For p1 As Integer = num To n - 1
For p2 As Integer = p1 + 1 To n
If Abs(b.element(p1,num))<Abs(b.element(p2,num)) Then
Swap r.element(p1),r.element(p2)
For g As Integer=1 To n
Swap b.element(p1,g),b.element(p2,g)
Next g
End If
Next p2
Next p1
#endmacro
For k As Integer=1 To n-1
pivot(k) 'full pivoting
For row As Integer =k To n-1
If b.element(row+1,k)=0 Then Exit For
Var f=b.element(k,k)/b.element(row+1,k)
r.element(row+1)=r.element(row+1)*f-r.element(k)
For g As Integer=1 To n
b.element((row+1),g)=b.element((row+1),g)*f-b.element(k,g)
Next g
Next row
Next k
'back substitute
For z As Integer=n To 1 Step -1
ans.element(z)=r.element(z)/b.element(z,z)
For j As Integer = n To z+1 Step -1
ans.element(z)=ans.element(z)-(b.element(z,j)*ans.element(j)/b.element(z,z))
Next j
Next z
EndFunction Sub= ans
End Function
'Interpolate through points.
Sub Interpolate(x_values() As Double,y_values() As Double,p() As Double)
Var n=Ubound(x_values)
Redim p(0):Redim p(1 To n)
Dim As Double matrix(1 To n,1 To n),rhs(1 To n)
For a As Integer=1 To n
rhs(a)=y_values(a)
For b As Integer=1 To n
matrix(a,b)=x_values(a)^(b-1)
Next b
Next a
'Solve the linear equations
GaussJordan(matrix(),rhs(),p())
End Sub
'======================== SET UP THE POINTS ===============
Dim As Double x(1 To ...)={0,1,2,3,4,5,6,7,8,9,10}
Dim As Double y(1 To ...)={1,6,17,34,57,86,121,162,209,262,321}
Redim As Double Poly(0)
'Get the polynomial Poly()
Interpolate(x(),y(),Poly())
'print coefficients to console
print "Polynomial Coefficients:"
print
For z As Integer=1 To Ubound(Poly)
If z=1 Then
Print "constant term ";tab(20);Poly(z)
Else
Print tab(8); "x^";z-1;" = ";tab(20);Poly(z)
End If
Next z
sleep</lang>
{{out}}
<pre>Polynomial Coefficients:
 
Function matrix.inverse() As matrix
constant term 1
Var ub1=Ubound(this.element,1),ub2=Ubound(this.element,2)
x^ 1 = 2
Dim As matrix x^ 2 = 3ans
Dim As vector x^ 3 = 0temp,null_
Redim temp.element(1 To ub1):Redim null_.element(1 To ub1)
x^ 4 = 0
Redim ans.element(1 To ub1,1 To ub2)
x^ 5 = 0
For a As x^ 6 Integer=1 To 0ub1
x^ 7 temp= 0null_
x^ 8 temp.element(a)= 01
x^ 9 temp= 0GaussJordan(temp)
x^ 10 = For b As Integer=1 To 0</pre>ub1
ans.element(b,a)=temp.element(b)
Next b
Next a
Return ans
End Function
 
'vandermode of x
Function vandermonde(x_values() As Double,w As Long) As matrix
Dim As matrix mat
Var n=Ubound(x_values)
Redim mat.element(1 To n,1 To w)
For a As Integer=1 To n
For b As Integer=1 To w
mat.element(a,b)=x_values(a)^(b-1)
Next b
Next a
Return mat
End Function
 
'main preocedure
Sub regress(x_values() As Double,y_values() As Double,ans() As Double,n As Long)
Redim ans(1 To Ubound(x_values))
Dim As matrix m1= vandermonde(x_values(),n)
Dim As matrix T=m1.transpose
Dim As vector y
Redim y.element(1 To Ubound(ans))
For n As Long=1 To Ubound(y_values)
y.element(n)=y_values(n)
Next n
Dim As vector result=(((T*m1).inverse)*T)*y
Redim Preserve ans(1 To n)
For n As Long=1 To Ubound(ans)
ans(n)=result.element(n)
Next n
End Sub
 
'Evaluate a polynomial at x
Function polyeval(Coefficients() As Double,Byval x As Double) As Double
Dim As Double acc
For i As Long=Ubound(Coefficients) To Lbound(Coefficients) Step -1
acc=acc*x+Coefficients(i)
Next i
Return acc
End Function
 
Function CRound(Byval x As Double,Byval precision As Integer=30) As String
If precision>30 Then precision=30
Dim As zstring * 40 z:Var s="%." &str(Abs(precision)) &"f"
sprintf(z,s,x)
If Val(z) Then Return Rtrim(Rtrim(z,"0"),".")Else Return "0"
End Function
 
Function show(a() As Double,places as long=10) As String
Dim As String s,g
For n As Long=Lbound(a) To Ubound(a)
If n<3 Then g="" Else g="^"+Str(n-1)
if val(cround(a(n),places))<>0 then
s+= Iif(Sgn(a(n))>=0,"+","")+cround(a(n),places)+ Iif(n=Lbound(a),"","*x"+g)+" "
end if
Next n
Return s
End Function
 
 
dim as double x(1 to ...)={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
dim as double y(1 to ...)={1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
 
Redim As Double ans()
regress(x(),y(),ans(),3)
 
print show(ans())
sleep</syntaxhighlight>
{{out}}
<pre>+1 +2*x +3*x^2</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">PolynomialRegression := function(x, y, n)
local a;
a := List([0 .. n], i -> List(x, s -> s^i));
Line 660 ⟶ 1,100:
# Return coefficients in ascending degree order
PolynomialRegression(x, y, 2);
# [ 1, 2, 3 ]</langsyntaxhighlight>
 
=={{header|gnuplot}}==
 
<langsyntaxhighlight lang="gnuplot"># The polynomial approximation
f(x) = a*x**2 + b*x + c
 
Line 687 ⟶ 1,127:
e
 
print sprintf("\n --- \n Polynomial fit: %.4f x^2 + %.4f x + %.4f\n", a, b, c)</langsyntaxhighlight>
 
=={{header|Go}}==
===Library gonum/matrix===
<langsyntaxhighlight lang="go">package main
 
import (
"fmt"
"log"
 
"gonum.org/v1/gonum/mat"
"github.com/gonum/matrix/mat64"
)
 
func main() {
var (
var (
x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
y x = []float64{10, 61, 172, 343, 574, 865, 1216, 1627, 2098, 2629, 32110}
y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
 
degree = 2
)
 
a = Vandermonde(x, degree+1)
func main() {
b = mat.NewDense(len(y), 1, y)
a := Vandermonde(x, degree)
c b := mat64mat.NewDense(len(y)degree+1, 1, ynil)
)
c := mat64.NewDense(degree+1, 1, nil)
 
var qr := new(mat64mat.QR)
qr.Factorize(a)
 
const trans = false
err := c.SolveQR(qr, false, b)
err := qr.SolveTo(c, trans, b)
if err != nil {
if err != nil {
fmt.Println(err)
log.Fatalf("could not solve QR: %+v", err)
} else {
}
fmt.Printf("%.3f\n", mat64.Formatted(c))
fmt.Printf("%.3f\n", mat.Formatted(c))
}
}
 
func Vandermonde(a []float64, degreed int) *mat64mat.Dense {
x := mat64mat.NewDense(len(a), degree+1d, nil)
for i := range a {
for j, p := 0, 1.0; j <= degreed; j, p = j+1, p*a[i] {
x.Set(i, j, p)
}
}
}
}
return x
}</langsyntaxhighlight>
{{out}}
<pre>
Line 740 ⟶ 1,181:
===Library go.matrix===
Least squares solution using QR decomposition and package [http://github.com/skelterjohn/go.matrix go.matrix].
<langsyntaxhighlight lang="go">package main
 
import (
Line 780 ⟶ 1,221:
}
fmt.Println(c)
}</langsyntaxhighlight>
{{out}} (lowest order coefficient first)
<pre>
Line 788 ⟶ 1,229:
=={{header|Haskell}}==
Uses module Matrix.LU from [http://hackage.haskell.org/package/dsp hackageDB DSP]
<langsyntaxhighlight lang="haskell">import Data.List
import Data.Array
import Control.Monad
Line 798 ⟶ 1,239:
polyfit d ry = elems $ solve mat vec where
mat = listArray ((1,1), (d,d)) $ liftM2 concatMap ppoly id [0..fromIntegral $ pred d]
vec = listArray (1,d) $ take d ry</langsyntaxhighlight>
{{out}} in GHCi:
<langsyntaxhighlight lang="haskell">*Main> polyfit 3 [1,6,17,34,57,86,121,162,209,262,321]
[1.0,2.0,3.0]</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">REAL :: n=10, x(n), y(n), m=3, p(m)
 
x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Line 818 ⟶ 1,259:
! called by the solver of the SOLVE function. All variables are global
Theory = p(1)*x(nr)^2 + p(2)*x(nr) + p(3)
END</langsyntaxhighlight>
{{out}}
<pre>SOLVE performs a (nonlinear) least-square fit (Levenberg-Marquardt):
Line 824 ⟶ 1,265:
 
=={{header|Hy}}==
<langsyntaxhighlight lang="lisp">(import [numpy [polyfit]])
 
(setv x (range 11))
(setv y [1 6 17 34 57 86 121 162 209 262 321])
 
(print (polyfit x y 2))</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight lang="j"> Y=:1 6 17 34 57 86 121 162 209 262 321
(%. ^/~@x:@i.@#) Y
1 2 3 0 0 0 0 0 0 0 0</langsyntaxhighlight>
 
Note that this implementation does not use floating point numbers,
Line 842 ⟶ 1,283:
but for small problems like this it is inconsequential.
 
The above solution fits a polynomial of order 11 (or, more specifically, a polynomial whose order matches the length of its argument sequence).
If the order of the polynomial is known to be 3
(as is implied in the task description)
then the following solution is probably preferable:
<langsyntaxhighlight lang="j"> Y %. (i.3) ^/~ i.#Y
1 2 3</langsyntaxhighlight>
(note that this time we used floating point numbers, so that result is approximate rather than exact - it only looks exact because of how J displays floating point numbers (by default, J assumes six digits of accuracy) - changing (i.3) to (x:i.3) would give us an exact result, if that mattered.)
 
=={{header|Java}}==
{{trans|D}}
{{works with|Java|8}}
<syntaxhighlight lang="java">import java.util.Arrays;
import java.util.function.IntToDoubleFunction;
import java.util.stream.IntStream;
 
public class PolynomialRegression {
private static void polyRegression(int[] x, int[] y) {
int n = x.length;
double xm = Arrays.stream(x).average().orElse(Double.NaN);
double ym = Arrays.stream(y).average().orElse(Double.NaN);
double x2m = Arrays.stream(x).map(a -> a * a).average().orElse(Double.NaN);
double x3m = Arrays.stream(x).map(a -> a * a * a).average().orElse(Double.NaN);
double x4m = Arrays.stream(x).map(a -> a * a * a * a).average().orElse(Double.NaN);
double xym = 0.0;
for (int i = 0; i < x.length && i < y.length; ++i) {
xym += x[i] * y[i];
}
xym /= Math.min(x.length, y.length);
double x2ym = 0.0;
for (int i = 0; i < x.length && i < y.length; ++i) {
x2ym += x[i] * x[i] * y[i];
}
x2ym /= Math.min(x.length, y.length);
 
double sxx = x2m - xm * xm;
double sxy = xym - xm * ym;
double sxx2 = x3m - xm * x2m;
double sx2x2 = x4m - x2m * x2m;
double sx2y = x2ym - x2m * ym;
 
double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
double a = ym - b * xm - c * x2m;
 
IntToDoubleFunction abc = (int xx) -> a + b * xx + c * xx * xx;
 
System.out.println("y = " + a + " + " + b + "x + " + c + "x^2");
System.out.println(" Input Approximation");
System.out.println(" x y y1");
for (int i = 0; i < n; ++i) {
System.out.printf("%2d %3d %5.1f\n", x[i], y[i], abc.applyAsDouble(x[i]));
}
}
 
public static void main(String[] args) {
int[] x = IntStream.range(0, 11).toArray();
int[] y = new int[]{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321};
polyRegression(x, y);
}
}</syntaxhighlight>
{{out}}
<pre>y = 1.0 + 2.0x + 3.0x^2
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0</pre>
 
=={{header|jq}}==
'''Adapted from [[#Wren|Wren]]'''
 
'''Works with jq, the C implementation of jq'''
 
'''Works with gojq, the Go implementation of jq'''
 
'''Works with jaq, the Rust implementation of jq'''
<syntaxhighlight lang="jq">
def mean: add/length;
 
def inner_product($y):
. as $x
| reduce range(0; length) as $i (0; . + ($x[$i] * $y[$i]));
 
# $x and $y should be arrays of the same length
# Emit { a, b, c, z}
# Attempt to avoid overflow
def polynomialRegression($x; $y):
($x | length) as $length
| ($length * $length) as $l2
| ($x | map(./$length)) as $xs
| ($xs | add) as $xm
| ($y | mean) as $ym
| ($xs | map(. * .) | add * $length) as $x2m
| ($x | map( (./$length) * . * .) | add) as $x3m
| ($xs | map(. * . | (.*.) ) | add * $l2 * $length) as $x4m
| ($xs | inner_product($y)) as $xym
| ($xs | map(. * .) | inner_product($y) * $length) as $x2ym
| ($x2m - $xm * $xm) as $sxx
| ($xym - $xm * $ym) as $sxy
| ($x3m - $xm * $x2m) as $sxx2
| ($x4m - $x2m * $x2m) as $sx2x2
| ($x2ym - $x2m * $ym) as $sx2y
| {z: ([$x,$y] | transpose) }
| .b = ($sxy * $sx2x2 - $sx2y * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2)
| .c = ($sx2y * $sxx - $sxy * $sxx2) / ($sxx * $sx2x2 - $sxx2 * $sxx2)
| .a = $ym - .b * $xm - .c * $x2m ;
 
# Input: {a,b,c,z}
def report:
def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .;
def abc($x): .a + .b * $x + .c * $x * $x;
def print($p): "\($p[0] | lpad(3)) \($p[1] | lpad(4)) \(abc($p[0]) | lpad(5))";
"y = \(.a) + \(.b)x + \(.c)x^2\n",
" Input Approximation",
" x y y\u0302",
print(.z[]) ;
def x: [range(0;11)];
def y: [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
 
polynomialRegression(x; y)
| report
</syntaxhighlight>
{{output}}
<pre>
y = 1 + 2x + 3x^2
 
Input Approximation
x y ŷ
0 1 1
1 6 6
2 17 17
3 34 34
4 57 57
5 86 86
6 121 121
7 162 162
8 209 209
9 262 262
10 321 321
</pre>
 
=={{header|Julia}}==
Line 854 ⟶ 1,439:
The least-squares fit problem for a degree <i>n</i>
can be solved with the built-in backslash operator (coefficients in increasing order of degree):
<langsyntaxhighlight lang="julia">polyfit(x::Vector, y::Vector, deg::Int) = collect(v ^ p for v in x, p in 0:deg) \ y
 
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
@show polyfit(x, y, 2)</langsyntaxhighlight>
 
{{out}}
Line 865 ⟶ 1,450:
=={{header|Kotlin}}==
{{trans|REXX}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
fun polyRegression(x: IntArray, y: IntArray) {
val n = x.size
val r = 0 until n
val xm = x.average()
val ym = y.average()
val x2m = rx.map { it * it }.average()
val x3m = rx.map { it * it * it }.average()
val x4m = rx.map { it * it * it * it }.average()
val xym = x.zip(y).map { it.first * it.second }.average()
val x2ym = x.zip(y).map { it.first * it.first * it.second }.average()
Line 893 ⟶ 1,476:
println(" Input Approximation")
println(" x y y1")
for (i(xi, yi) in 0x untilzip ny) {
System.out.printf("%2d %3d %5.1f\n", x[i]xi, y[i]yi, abc(x[i]xi))
}
}
 
fun main(args: Array<String>) {
val x = IntArray(11) { it }
val y = intArrayOf(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
polyRegression(x, y)
}</langsyntaxhighlight>
 
{{out}}
Line 923 ⟶ 1,506:
</pre>
 
=={{header|MathematicaLua}}==
{{trans|Modula-2}}
Using the built-in "Fit" function.
<syntaxhighlight lang="lua">function eval(a,b,c,x)
return a + (b + c * x) * x
end
 
function regression(xa,ya)
<lang Mathematica>data = Transpose@{Range[0, 10], {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}};
local n = #xa
Fit[data, {1, x, x^2}, x]</lang>
 
local xm = 0.0
local ym = 0.0
local x2m = 0.0
local x3m = 0.0
local x4m = 0.0
local xym = 0.0
local x2ym = 0.0
 
for i=1,n do
xm = xm + xa[i]
ym = ym + ya[i]
x2m = x2m + xa[i] * xa[i]
x3m = x3m + xa[i] * xa[i] * xa[i]
x4m = x4m + xa[i] * xa[i] * xa[i] * xa[i]
xym = xym + xa[i] * ya[i]
x2ym = x2ym + xa[i] * xa[i] * ya[i]
end
xm = xm / n
ym = ym / n
x2m = x2m / n
x3m = x3m / n
x4m = x4m / n
xym = xym / n
x2ym = x2ym / n
 
local sxx = x2m - xm * xm
local sxy = xym - xm * ym
local sxx2 = x3m - xm * x2m
local sx2x2 = x4m - x2m * x2m
local sx2y = x2ym - x2m * ym
 
local b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
local c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
local a = ym - b * xm - c * x2m
 
print("y = "..a.." + "..b.."x + "..c.."x^2")
for i=1,n do
print(string.format("%2d %3d %3d", xa[i], ya[i], eval(a, b, c, xa[i])))
end
end
 
local xa = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local ya = {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}
regression(xa, ya)</syntaxhighlight>
{{out}}
<pre>y = 1 + 2x + 3x^2
0 1 1
1 6 6
2 17 17
3 34 34
4 57 57
5 86 86
6 121 121
7 162 162
8 209 209
9 262 262
10 321 321</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">with(CurveFitting);
PolynomialInterpolation([[0, 1], [1, 6], [2, 17], [3, 34], [4, 57], [5, 86], [6, 121], [7, 162], [8, 209], [9, 262], [10, 321]], 'x');
</syntaxhighlight>
Result:
<pre>3*x^2+2*x+1</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Using the built-in "Fit" function.
<syntaxhighlight lang="mathematica">data = Transpose@{Range[0, 10], {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}};
Fit[data, {1, x, x^2}, x]</syntaxhighlight>
Second version: using built-in "InterpolatingPolynomial" function.
<syntaxhighlight lang="mathematica">Simplify@InterpolatingPolynomial[{{0, 1}, {1, 6}, {2, 17}, {3, 34}, {4, 57}, {5, 86}, {6, 121}, {7, 162}, {8, 209}, {9, 262}, {10, 321}}, x]</syntaxhighlight>
WolframAlpha version:
<syntaxhighlight lang="mathematica">curve fit (0,1), (1,6), (2,17), (3,34), (4,57), (5,86), (6,121), (7,162), (8,209), (9,262), (10,321)</syntaxhighlight>
Result:
<pre>1 + 2x + 3x^2</pre>
Line 936 ⟶ 1,597:
The output of this function is the coefficients of the polynomial which best fit these x,y value pairs.
 
<langsyntaxhighlight MATLABlang="matlab">>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
>> y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
>> polyfit(x,y,2)
Line 942 ⟶ 1,603:
ans =
 
2.999999999999998 2.000000000000019 0.999999999999956</langsyntaxhighlight>
 
=={{header|МК-61/52}}==
Part 1:
<syntaxhighlight lang="text">ПC С/П ПD ИП9 + П9 ИПC ИП5 + П5
ИПC x^2 П2 ИП6 + П6 ИП2 ИПC * ИП7
+ П7 ИП2 x^2 ИП8 + П8 ИПC ИПD *
ИПA + ПA ИП2 ИПD * ИПB + ПB ИПD
КИП4 С/П БП 00</langsyntaxhighlight>
 
''Input'': В/О x<sub>1</sub> С/П y<sub>1</sub> С/П x<sub>2</sub> С/П y<sub>2</sub> С/П ...
 
Part 2:
<syntaxhighlight lang="text">ИП5 ПC ИП6 ПD П2 ИП7 П3 ИП4 ИПD *
ИПC ИП5 * - ПD ИП4 ИП7 * ИПC ИП6
* - П7 ИП4 ИПA * ИПC ИП9 * -
Line 963 ⟶ 1,624:
ИПD ИП8 * ИП7 ИП3 * - / ПB ИПA
ИПB ИП7 * - ИПD / ПA ИП9 ИПB ИП6
* - ИПA ИП5 * - ИП4 / П9 С/П</langsyntaxhighlight>
 
''Result'': Р9 = a<sub>0</sub>, РA = a<sub>1</sub>, РB = a<sub>2</sub>.
 
=={{header|OctaveModula-2}}==
<syntaxhighlight lang="modula2">MODULE PolynomialRegression;
FROM FormatString IMPORT FormatString;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
 
PROCEDURE Eval(a,b,c,x : REAL) : REAL;
<lang octave>x = [0:10];
BEGIN
y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
RETURN a + b*x + c*x*x;
coeffs = polyfit(x, y, 2)</lang>
END Eval;
 
PROCEDURE Regression(x,y : ARRAY OF INTEGER);
=={{header|PARI/GP}}==
VAR
Lagrange interpolating polynomial:
n,i : INTEGER;
<lang parigp>polinterpolate([0,1,2,3,4,5,6,7,8,9,10],[1,6,17,34,57,86,121,162,209,262,321])</lang>
xm,x2m,x3m,x4m : REAL;
In newer versions, this can be abbreviated:
ym : REAL;
<lang parigp>polinterpolate([0..10],[1,6,17,34,57,86,121,162,209,262,321])</lang>
xym,x2ym : REAL;
{{out}}
sxx,sxy,sxx2,sx2x2,sx2y : REAL;
<pre>3*x^2 + 2*x + 1</pre>
a,b,c : REAL;
buf : ARRAY[0..63] OF CHAR;
BEGIN
n := SIZE(x)/SIZE(INTEGER);
 
xm := 0.0;
Least-squares fit:
ym := 0.0;
<lang parigp>V=[1,6,17,34,57,86,121,162,209,262,321]~;
x2m := 0.0;
M=matrix(#V,3,i,j,(i-1)^(j-1));Polrev(matsolve(M~*M,M~*V))</lang>
x3m := 0.0;
<small>Code thanks to [http://pari.math.u-bordeaux.fr/archives/pari-users-1105/msg00006.html Bill Allombert]</small>
x4m := 0.0;
{{out}}
xym := 0.0;
<pre>3*x^2 + 2*x + 1</pre>
x2ym := 0.0;
FOR i:=0 TO n-1 DO
xm := xm + FLOAT(x[i]);
ym := ym + FLOAT(y[i]);
x2m := x2m + FLOAT(x[i]) * FLOAT(x[i]);
x3m := x3m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]);
x4m := x4m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]);
xym := xym + FLOAT(x[i]) * FLOAT(y[i]);
x2ym := x2ym + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(y[i]);
END;
xm := xm / FLOAT(n);
ym := ym / FLOAT(n);
x2m := x2m / FLOAT(n);
x3m := x3m / FLOAT(n);
x4m := x4m / FLOAT(n);
xym := xym / FLOAT(n);
x2ym := x2ym / FLOAT(n);
 
sxx := x2m - xm * xm;
Least-squares polynomial fit in its own function:
sxy := xym - xm * ym;
<lang parigp>lsf(X,Y,n)=my(M=matrix(#X,n+1,i,j,X[i]^(j-1))); Polrev(matsolve(M~*M,M~*Y~))
sxx2 := x3m - xm * x2m;
lsf([0..10], [1,6,17,34,57,86,121,162,209,262,321], 2)</lang>
sx2x2 := x4m - x2m * x2m;
sx2y := x2ym - x2m * ym;
 
b := (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
=={{header|Perl}}==
c := (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2);
This script depends on the Math::MatrixReal CPAN module to compute matrix determinants.
a := ym - b * xm - c * x2m;
<lang Perl>
#!bin/usr/perl
use strict;
use warnings;
use 5.020;
 
WriteString("y = ");
#This is a script to calculate an equation for a given set of coordinates.
RealToStr(a, buf);
#Input will be taken in sets of x and y. It can handle a grand total of 26 pairs.
WriteString(buf);
#For matrix functions, we depend on the Math::MatrixReal package.
WriteString(" + ");
use Math::MatrixReal;
RealToStr(b, buf);
WriteString(buf);
WriteString("x + ");
RealToStr(c, buf);
WriteString(buf);
WriteString("x^2");
WriteLn;
 
FOR i:=0 TO n-1 DO
=pod
FormatString("%2i %3i ", buf, x[i], y[i]);
Step 1: Get each x coordinate all at once (delimited by " ") and each for y at once
WriteString(buf);
on the next prompt in the same format (delimited by " ").
RealToStr(Eval(a,b,c,FLOAT(x[i])), buf);
=cut
WriteString(buf);
sub getPairs() {
my $buffer = <STDIN> WriteLn;
chomp($buffer)END;
END Regression;
return split(" ", $buffer);
}
say("Please enter the values for the x coordinates, each delimited by a space. \(Ex: 0 1 2 3\)");
my @x = getPairs();
say("Please enter the values for the y coordinates, each delimited by a space. \(Ex: 0 1 2 3\)");
my @y = getPairs();
#This whole thing depends on the number of x's being the same as the number of y's
my $pairs = scalar(@x);
 
TYPE R = ARRAY[0..10] OF INTEGER;
VAR
x,y : R;
BEGIN
x := R{0,1,2,3,4,5,6,7,8,9,10};
y := R{1,6,17,34,57,86,121,162,209,262,321};
Regression(x,y);
 
ReadChar;
=pod
END PolynomialRegression.</syntaxhighlight>
Step 2: Devise the base equation of our polynomial using the following idea
There is some polynomial of degree n (n == number of pairs - 1) such that
f(x)=ax^n + bx^(n-1) + ... yx + z
=cut
#Create an array of coefficients and their degrees with the format ("coefficent degree")
my @alphabet;
my @degrees;
for(my $alpha = "a", my $degree = $pairs - 1; $degree >= 0; $degree--, $alpha++) {
push(@alphabet, "$alpha");
push(@degrees, "$degree");
}
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import lenientops, sequtils, stats, strformat
 
proc polyRegression(x, y: openArray[int]) =
=pod
Step 3: Using the array of coeffs and their degrees, set up individual equations solving for
each coordinate pair. Why put it in this format? It interfaces witht he Math::MatrixReal package better this way.
=cut
my @coeffs;
for(my $count = 0; $count < $pairs; $count++) {
my $buffer = "[ ";
foreach (@degrees) {
$buffer .= (($x[$count] ** $_) . " ");
}
push(@coeffs, ($buffer . "]"));
}
my $row;
foreach (@coeffs) {
$row .= ("$_\n");
}
 
let xm = mean(x)
let ym = mean(y)
let x2m = mean(x.mapIt(it * it))
let x3m = mean(x.mapIt(it * it * it))
let x4m = mean(x.mapIt(it * it * it * it))
let xym = mean(zip(x, y).mapIt(it[0] * it[1]))
let x2ym = mean(zip(x, y).mapIt(it[0] * it[0] * it[1]))
 
let sxx = x2m - xm * xm
=pod
let sxy = xym - xm * ym
Step 4: We now have rows of x's raised to powers. With this in mind, we create a coefficient matrix.
let sxx2 = x3m - xm * x2m
=cut
let sx2x2 = x4m - x2m * x2m
my $matrix = Math::MatrixReal->new_from_string($row);
let sx2y = x2ym - x2m * ym
my $buffMatrix = $matrix->new_from_string($row);
 
let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let a = ym - b * xm - c * x2m
 
func abc(x: int): float = a + b * x + c * x * x
=pod
Step 5: Now that we've gotten the matrix to do what we want it to do, we need to calculate the various determinants of the matrices
=cut
my $coeffDet = $matrix->det();
 
echo &"y = {a} + {b}x + {c}x²\n"
echo " Input Approximation"
echo " x y y1"
for (xi, yi) in zip(x, y):
echo &"{xi:2} {yi:3} {abc(xi):5}"
 
=pod
Step 6: Now that we have the determinant of the coefficient matrix, we need to find the determinants of the coefficient matrix with each column (1 at a time) replaced with the y values.
=cut
#NOTE: Unlike in Perl, matrix indices start at 1, not 0.
for(my $rows = my $column = 1; $column <= $pairs; $column++) {
#Reassign the values in the current column to the y values
foreach (@y) {
$buffMatrix->assign($rows, $column, $_);
$rows++;
}
#Find the values for the variables a, b, ... y, z in the original polynomial
#To round the difference of the determinants, I had to get creative
my $buffDet = $buffMatrix->det() / $coeffDet;
my $tempDet = int(abs($buffDet) + .5);
$alphabet[$column - 1] = $buffDet >= 0 ? $tempDet : 0 - $tempDet;
#Reset the buffer matrix and the row counter
$buffMatrix = $matrix->new_from_string($row);
$rows = 1;
}
 
let x = toSeq(0..10)
let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
polyRegression(x, y)</syntaxhighlight>
 
{{out}}
=pod
<pre>y = 1.0 + 2.0x + 3.0x²
Step 7: Now that we've found the values of a, b, ... y, z of the original polynomial, it's time to form our polynomial!
=cut
my $polynomial;
for(my $i = 0; $i < $pairs-1; $i++) {
if($alphabet[$i] == 0) {
next;
}
if($alphabet[$i] == 1) {
$polynomial .= ($degrees[$i] . " + ");
}
if($degrees[$i] == 1) {
$polynomial .= ($alphabet[$i] . "x" . " + ");
}
else {
$polynomial .= ($alphabet[$i] . "x^" . $degrees[$i] . " + ");
}
}
#Now for the last piece of the poly: the y-intercept.
$polynomial .= $alphabet[scalar(@alphabet)-1];
 
Input Approximation
print("An approximating polynomial for your dataset is $polynomial.\n");
x y y1
</lang>
0 1 1
{{output}}
1 6 6
<pre>
2 17 17
Please enter the values for the x coordinates, each delimited by a space. (Ex: 0 1 2 3)
0 1 2 3 4 534 6 7 8 9 1034
4 57 57
Please enter the values for the y coordinates, each delimited by a space. (Ex: 0 1 2 3)
1 5 6 17 34 57 86 121 162 209 262 32186
6 121 121
An approximating polynomial for your dataset is 3x^2 + 2x + 1.
7 162 162
</pre>
8 209 209
9 262 262
10 321 321</pre>
 
=={{header|Perl 6OCaml}}==
{{trans|Kotlin}}
We'll use a Clifford algebra library.
{{libheader|Base}}
<syntaxhighlight lang="ocaml">open Base
open Stdio
 
let mean fa =
<lang perl6>use Clifford;
let open Float in
(Array.reduce_exn fa ~f:(+)) / (of_int (Array.length fa))
 
let regression xs ys =
constant @x1 = <0 1 2 3 4 5 6 7 8 9 10>;
let open Float in
constant @y = <1 6 17 34 57 86 121 162 209 262 321>;
let xm = mean xs in
let ym = mean ys in
let x2m = Array.map xs ~f:(fun x -> x * x) |> mean in
let x3m = Array.map xs ~f:(fun x -> x * x * x) |> mean in
let x4m = Array.map xs ~f:(fun x -> let x2 = x * x in x2 * x2) |> mean in
let xzipy = Array.zip_exn xs ys in
let xym = Array.map xzipy ~f:(fun (x, y) -> x * y) |> mean in
let x2ym = Array.map xzipy ~f:(fun (x, y) -> x * x * y) |> mean in
 
let sxx = x2m - xm * xm in
constant $x0 = [+] @e[^@x1];
constant $x1 let sxy = [+]xym @x1- xm Z* @e;ym in
constant $x2 =let [+]sxx2 @x1= »**»x3m 2- xm Z* @e;x2m in
let sx2x2 = x4m - x2m * x2m in
let sx2y = x2ym - x2m * ym in
 
let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) in
constant $y = [+] @y Z* @e;
let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) in
let a = ym - b * xm - c * x2m in
 
let abc xx = a + b * xx + c * xx * xx in
my $J = $x1 ∧ $x2;
my $I = $x0 ∧ $J;
 
printf "y = %.1f + %.1fx + %.1fx^2\n\n" a b c;
my $I2 = ($I·$I.reversion).Real;
printf " Input Approximation\n";
printf " x y y1\n";
Array.iter xzipy ~f:(fun (xi, yi) ->
printf "%2g %3g %5.1f\n" xi yi (abc xi)
)
 
let () =
let x = Array.init 11 ~f:Float.of_int in
let y = [| 1.; 6.; 17.; 34.; 57.; 86.; 121.; 162.; 209.; 262.; 321. |] in
regression x y</syntaxhighlight>
 
.say for
(($y ∧ $J)·$I.reversion)/$I2,
(($y ∧ ($x2 ∧ $x0))·$I.reversion)/$I2,
(($y ∧ ($x0 ∧ $x1))·$I.reversion)/$I2;</lang>
{{out}}
<pre>1
y = 1.0 + 2.0x + 3.0x^2
2
 
3
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0
</pre>
 
=={{header|PhixOctave}}==
{{trans|REXX}}
<lang Phix>constant x = {0,1,2,3,4,5,6,7,8,9,10}
constant y = {1,6,17,34,57,86,121,162,209,262,321}
constant n = length(x)
 
<syntaxhighlight lang="octave">x = [0:10];
function regression()
atomy {xm= [1, ym 6, x2m 17, x3m 34, x4m 57, xym 86, x2ym}121, @=162, 209, 262, 0321];
coeffs = polyfit(x, y, 2)</syntaxhighlight>
for i=1 to n do
atom xi = x[i],
yi = y[i]
xm += xi
ym += yi
x2m += power(xi,2)
x3m += power(xi,3)
x4m += power(xi,4)
xym += xi*yi
x2ym += power(xi,2)*yi
end for
xm /= n
ym /= n
x2m /= n
x3m /= n
x4m /= n
xym /= n
x2ym /= n
atom Sxx = x2m-power(xm,2),
Sxy = xym-xm*ym,
Sxx2 = x3m-xm*x2m,
Sx2x2 = x4m-power(x2m,2),
Sx2y = x2ym-x2m*ym,
B = (Sxy*Sx2x2-Sx2y*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)),
C = (Sx2y*Sxx-Sxy*Sxx2)/(Sxx*Sx2x2-power(Sxx2,2)),
A = ym-B*xm-C*x2m
return {C,B,A}
end function
 
=={{header|PARI/GP}}==
atom {a,b,c} = regression()
Lagrange interpolating polynomial:
<syntaxhighlight lang="parigp">polinterpolate([0,1,2,3,4,5,6,7,8,9,10],[1,6,17,34,57,86,121,162,209,262,321])</syntaxhighlight>
In newer versions, this can be abbreviated:
<syntaxhighlight lang="parigp">polinterpolate([0..10],[1,6,17,34,57,86,121,162,209,262,321])</syntaxhighlight>
{{out}}
<pre>3*x^2 + 2*x + 1</pre>
 
Least-squares fit:
function f(atom x)
<syntaxhighlight lang="parigp">V=[1,6,17,34,57,86,121,162,209,262,321]~;
return a*x*x+b*x+c
M=matrix(#V,3,i,j,(i-1)^(j-1));Polrev(matsolve(M~*M,M~*V))</syntaxhighlight>
end function
<small>Code thanks to [http://pari.math.u-bordeaux.fr/archives/pari-users-1105/msg00006.html Bill Allombert]</small>
{{out}}
<pre>3*x^2 + 2*x + 1</pre>
 
Least-squares polynomial fit in its own function:
printf(1,"y=%gx^2+%gx+%g\n",{a,b,c})
<syntaxhighlight lang="parigp">lsf(X,Y,n)=my(M=matrix(#X,n+1,i,j,X[i]^(j-1))); Polrev(matsolve(M~*M,M~*Y~))
printf(1,"\n x y f(x)\n")
lsf([0..10], [1,6,17,34,57,86,121,162,209,262,321], 2)</syntaxhighlight>
for i=1 to n do
 
printf(1," %2d %3d %3g\n",{x[i],y[i],f(x[i])})
=={{header|Perl}}==
end for</lang>
This code identical to that of [[Multiple regression]] task.
<syntaxhighlight lang="perl">use strict;
use warnings;
use Statistics::Regression;
 
my @x = <0 1 2 3 4 5 6 7 8 9 10>;
my @y = <1 6 17 34 57 86 121 162 209 262 321>;
 
my @model = ('const', 'X', 'X**2');
 
my $reg = Statistics::Regression->new( '', [@model] );
$reg->include( $y[$_], [ 1.0, $x[$_], $x[$_]**2 ]) for 0..@y-1;
my @coeff = $reg->theta();
 
printf "%-6s %8.3f\n", $model[$_], $coeff[$_] for 0..@model-1;</syntaxhighlight>
{{output}}
<pre>const 1.000
X 2.000
X**2 3.000</pre>
 
PDL Alternative:
<syntaxhighlight lang="perl">#!/usr/bin/perl -w
use strict;
 
use PDL;
use PDL::Math;
use PDL::Fit::Polynomial;
 
my $x = float [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
my $y = float [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321];
# above will output: 3.00000037788248 * $x**2 + 1.99999750988868 * $x + 1.00000180493936
 
# $x = float [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
# $y = float [ 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0];
# above correctly returns: " 1.08484845125187 * $x**2 + 10.3551513321297 * $x-0.616363852007752 "
 
my ($yfit, $coeffs) = fitpoly1d $x, $y, 3; # 3rd degree
 
foreach (reverse(0..$coeffs->dim(0)-1)) {
print " +" unless(($coeffs->at($_) <0) || $_==$coeffs->dim(0)-1); # let the unary minus replace the + operator
print " ";
print $coeffs->at($_);
print " * \$x" if($_);
print "**$_" if($_>1);
print "\n" unless($_)
}
</syntaxhighlight>
{{output}}
<pre> 3.00000037788248 * $x**2 + 1.99999750988868 * $x + 1.00000180493936</pre>
 
=={{header|Phix}}==
{{trans|REXX}}
{{libheader|Phix/online}}
{{libheader|Phix/pGUI}}
You can run this online [http://phix.x10.mx/p2js/Polynomial_regression.htm here].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Polynomial_regression.exw</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">,</span><span style="color: #000000;">34</span><span style="color: #0000FF;">,</span><span style="color: #000000;">57</span><span style="color: #0000FF;">,</span><span style="color: #000000;">86</span><span style="color: #0000FF;">,</span><span style="color: #000000;">121</span><span style="color: #0000FF;">,</span><span style="color: #000000;">162</span><span style="color: #0000FF;">,</span><span style="color: #000000;">209</span><span style="color: #0000FF;">,</span><span style="color: #000000;">262</span><span style="color: #0000FF;">,</span><span style="color: #000000;">321</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">regression</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">xm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ym</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x3m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x4m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">xym</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x2ym</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">xi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">yi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">xm</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">xi</span>
<span style="color: #000000;">ym</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">yi</span>
<span style="color: #000000;">x2m</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">x3m</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">x4m</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">xym</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">xi</span><span style="color: #0000FF;">*</span><span style="color: #000000;">yi</span>
<span style="color: #000000;">x2ym</span> <span style="color: #0000FF;">+=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xi</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">yi</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">xm</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">ym</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">x2m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">x3m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">x4m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">xym</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #000000;">x2ym</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">n</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">Sxx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x2m</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">xm</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">Sxy</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">xym</span><span style="color: #0000FF;">-</span><span style="color: #000000;">xm</span><span style="color: #0000FF;">*</span><span style="color: #000000;">ym</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">Sxx2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x3m</span><span style="color: #0000FF;">-</span><span style="color: #000000;">xm</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x2m</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">Sx2x2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x4m</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x2m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">Sx2y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">x2ym</span><span style="color: #0000FF;">-</span><span style="color: #000000;">x2m</span><span style="color: #0000FF;">*</span><span style="color: #000000;">ym</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">B</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">Sxy</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sx2x2</span><span style="color: #0000FF;">-</span><span style="color: #000000;">Sx2y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sxx2</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">Sxx</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sx2x2</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Sxx2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">C</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">Sx2y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sxx</span><span style="color: #0000FF;">-</span><span style="color: #000000;">Sxy</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sxx2</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">Sxx</span><span style="color: #0000FF;">*</span><span style="color: #000000;">Sx2x2</span><span style="color: #0000FF;">-</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">Sxx2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">A</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ym</span><span style="color: #0000FF;">-</span><span style="color: #000000;">B</span><span style="color: #0000FF;">*</span><span style="color: #000000;">xm</span><span style="color: #0000FF;">-</span><span style="color: #000000;">C</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x2m</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">C</span><span style="color: #0000FF;">,</span><span style="color: #000000;">B</span><span style="color: #0000FF;">,</span><span style="color: #000000;">A</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #004080;">atom</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">regression</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">b</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">c</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"y=%gx^2+%gx+%g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n x y f(x)\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" %2d %3d %3g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">y</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- And a simple plot (re-using x,y from above)</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">IupGraph</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">get_data</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">graph</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">w</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">graph</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">graph</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YTICK"</span><span style="color: #0000FF;">,</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;"><</span><span style="color: #000000;">240</span><span style="color: #0000FF;">?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;"><</span><span style="color: #000000;">150</span><span style="color: #0000FF;">?</span><span style="color: #000000;">80</span><span style="color: #0000FF;">:</span><span style="color: #000000;">40</span><span style="color: #0000FF;">):</span><span style="color: #000000;">20</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #004600;">CD_RED</span><span style="color: #0000FF;">}}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">graph</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">IupGraph</span><span style="color: #0000FF;">(</span><span style="color: #000000;">get_data</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"RASTERSIZE=640x440"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">graph</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"XTICK=1,XMIN=0,XMAX=10"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">graph</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YTICK=20,YMIN=0,YMAX=320"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">graph</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="simple plot"`</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttributes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"MINSIZE=245x150"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</syntaxhighlight>-->
{{out}}
(plus a simple graphical plot, as per [[Polynomial_regression#Racket|Racket]])
<pre>
y=3x^2+2x+1
Line 1,214 ⟶ 2,007:
10 321 321
</pre>
Alternatively, a simple plot, (as per [[Polynomial_regression#Racket|Racket]]):
{{libheader|pGUI}}
<lang Phix>include pGUI.e
 
=={{header|PowerShell}}==
constant x = {0,1,2,3,4,5,6,7,8,9,10}
<syntaxhighlight lang="powershell">
constant y = {1,6,17,34,57,86,121,162,209,262,321}
function qr([double[][]]$A) {
$m,$n = $A.count, $A[0].count
$pm,$pn = ($m-1), ($n-1)
[double[][]]$Q = 0..($m-1) | foreach{$row = @(0) * $m; $row[$_] = 1; ,$row}
[double[][]]$R = $A | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
foreach ($h in 0..$pn) {
[double[]]$u = $R[$h..$pm] | foreach{$_[$h]}
[double]$nu = $u | foreach {[double]$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
$u[0] -= if ($u[0] -lt 1) {$nu} else {-$nu}
[double]$nu = $u | foreach {$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)}
[double[]]$u = $u | foreach { $_/$nu}
[double[][]]$v = 0..($u.Count - 1) | foreach{$i = $_; ,($u | foreach{2*$u[$i]*$_})}
[double[][]]$CR = $R | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}
[double[][]]$CQ = $Q | foreach{$row = $_; ,@(0..$pm | foreach{$row[$_]})}
foreach ($i in $h..$pm) {
foreach ($j in $h..$pn) {
$R[$i][$j] -= $h..$pm | foreach {[double]$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CR[$_][$j]} {$sum}
}
}
if (0 -eq $h) {
foreach ($i in $h..$pm) {
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i][$_]*$CQ[$_][$j]} {$sum}
}
}
} else {
$p = $h-1
foreach ($i in $h..$pm) {
foreach ($j in 0..$p) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
foreach ($j in $h..$pm) {
$Q[$i][$j] -= $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}
}
}
}
}
foreach ($i in 0..$pm) {
foreach ($j in $i..$pm) {$Q[$i][$j],$Q[$j][$i] = $Q[$j][$i],$Q[$i][$j]}
}
[PSCustomObject]@{"Q" = $Q; "R" = $R}
}
 
function leastsquares([Double[][]]$A,[Double[]]$y) {
IupOpen()
$QR = qr $A
[Double[][]]$Q = $QR.Q
[Double[][]]$R = $QR.R
$m,$n = $A.count, $A[0].count
[Double[]]$z = foreach ($j in 0..($m-1)) {
0..($m-1) | foreach {$sum = 0} {$sum += $Q[$_][$j]*$y[$_]} {$sum}
}
[Double[]]$x = @(0)*$n
for ($i = $n-1; $i -ge 0; $i--) {
for ($j = $i+1; $j -lt $n; $j++) {
$z[$i] -= $x[$j]*$R[$i][$j]
}
$x[$i] = $z[$i]/$R[$i][$i]
}
$x
}
 
function polyfit([Double[]]$x,[Double[]]$y,$n) {
Ihandle plot = IupPlot("GRID=YES, MARGINLEFT=50, MARGINBOTTOM=40")
$m = $x.Count
-- (just add ", AXS_YSCALE=LOG10" for a nice log scale)
[Double[][]]$A = 0..($m-1) | foreach{$row = @(1) * ($n+1); ,$row}
IupPlotBegin(plot, 0)
for ($i =1 to0; length(x$i -lt $m; $i++) do{
for ($j = $n-1; 0 -le $j; $j--) {
IupPlotAdd(plot, x[i], y[i])
$A[$i][$j] = $A[$i][$j+1]*$x[$i]
end for
}
{} = IupPlotEnd(plot)
}
leastsquares $A $y
}
 
function show($m) {$m | foreach {write-host "$_"}}
Ihandle dlg = IupDialog(plot)
IupSetAttributes(dlg, "RASTERSIZE=%dx%d", {640, 480})
IupSetAttribute(dlg, "TITLE", "simple plot")
IupShow(dlg)
 
$A = @(@(12,-51,4), @(6,167,-68), @(-4,24,-41))
IupMainLoop()
$x = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
IupClose()</lang>
$y = @(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
"polyfit "
"X^2 X constant"
"$(polyfit $x $y 2)"
</syntaxhighlight>
{{out}}
<pre>
polyfit
X^2 X constant
3 1.99999999999998 1.00000000000005
</pre>
 
=={{header|Python}}==
 
{{libheader|numpyNumPy}}
<langsyntaxhighlight lang="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]
>>> coeffs = numpy.polyfit(x,y,deg=2)
>>> coeffs
array([ 3., 2., 1.])</langsyntaxhighlight>
Substitute back received coefficients.
<langsyntaxhighlight lang="python">>>> yf = numpy.polyval(numpy.poly1d(coeffs), x)
>>> yf
array([ 1., 6., 17., 34., 57., 86., 121., 162., 209., 262., 321.])</langsyntaxhighlight>
Find max absolute error:
<langsyntaxhighlight lang="python">>>> '%.1g' % max(y-yf)
'1e-013'</langsyntaxhighlight>
 
===Example===
For input arrays `x' and `y':
<langsyntaxhighlight lang="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]</langsyntaxhighlight>
 
<langsyntaxhighlight lang="python">>>> p = numpy.poly1d(numpy.polyfit(x, y, deg=2), variable='N')
>>> print p
2
1.085 N + 10.36 N - 0.6164</langsyntaxhighlight>
Thus we confirm once more that for already sorted sequences
the considered quick sort implementation has
Line 1,275 ⟶ 2,134:
which will find the least squares solution via a QR decomposition:
 
<syntaxhighlight lang="r">
<lang R>
x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)
coef(lm(y ~ x + I(x^2)))</langsyntaxhighlight>
 
{{out}}
Line 1,288 ⟶ 2,147:
Alternately, use poly:
 
<langsyntaxhighlight Rlang="r">coef(lm(y ~ poly(x, 2, raw=T)))</langsyntaxhighlight>{{out}}
<pre> (Intercept) poly(x, 2, raw = T)1 poly(x, 2, raw = T)2
1 2 3</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math plot)
Line 1,312 ⟶ 2,171:
(plot (list (points (map vector xs ys))
(function (poly (fit xs ys 2)))))
</syntaxhighlight>
</lang>
{{out}}
[[File:polyreg-racket.png]]
 
=={{header|Raku}}==
(formerly Perl 6)
We'll use a Clifford algebra library. Very slow.
 
Rationale (in French for some reason):
 
Le système d'équations peut s'écrire :
<math>\left(a + b x_i + cx_i^2 = y_i\right)_{i=1\ldots N}</math>, où on cherche <math>(a,b,c)\in\mathbb{R}^3</math>. On considère <math>\mathbb{R}^N</math> et on répartit chaque équation sur chaque dimension:
 
<math> (a + b x_i + cx_i^2)\mathbf{e}_i = y_i\mathbf{e}_i</math>
 
Posons alors :
 
<math>
\mathbf{x}_0 = \sum_{i=1}^N \mathbf{e}_i,\,
\mathbf{x}_1 = \sum_{i=1}^N x_i\mathbf{e}_i,\,
\mathbf{x}_2 = \sum_{i=1}^N x_i^2\mathbf{e}_i,\,
\mathbf{y} = \sum_{i=1}^N y_i\mathbf{e}_i
</math>
 
Le système d'équations devient : <math>a\mathbf{x}_0+b\mathbf{x}_1+c\mathbf{x}_2 = \mathbf{y}</math>.
 
D'où :
<math>\begin{align}
a = \mathbf{y}\and\mathbf{x}_1\and\mathbf{x}_2/(\mathbf{x}_0\and\mathbf{x_1}\and\mathbf{x_2})\\
b = \mathbf{y}\and\mathbf{x}_2\and\mathbf{x}_0/(\mathbf{x}_1\and\mathbf{x_2}\and\mathbf{x_0})\\
c = \mathbf{y}\and\mathbf{x}_0\and\mathbf{x}_1/(\mathbf{x}_2\and\mathbf{x_0}\and\mathbf{x_1})\\
\end{align}</math>
 
<syntaxhighlight lang="raku" line>use MultiVector;
 
constant @x1 = <0 1 2 3 4 5 6 7 8 9 10>;
constant @y = <1 6 17 34 57 86 121 162 209 262 321>;
 
constant $x0 = [+] @e[^@x1];
constant $x1 = [+] @x1 Z* @e;
constant $x2 = [+] @x1 »**» 2 Z* @e;
 
constant $y = [+] @y Z* @e;
 
.say for
$y∧$x1∧$x2/($x0∧$x1∧$x2),
$y∧$x2∧$x0/($x1∧$x2∧$x0),
$y∧$x0∧$x1/($x2∧$x0∧$x1);
</syntaxhighlight>
{{out}}
<pre>1
2
3
</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* Implementation of http://keisan.casio.com/exec/system/14059932254941
*--------------------------------------------------------------------*/
Line 1,367 ⟶ 2,277:
fun:
Parse Arg x
Return a+b*x+c*x**2 </langsyntaxhighlight>
{{out}}
<pre>y=1+2*x+3*x**2
Line 1,383 ⟶ 2,293:
9 262 262.000
10 321 321.000</pre>
 
=={{header|RPL}}==
{{trans|Ada}}
≪ 1 + → x y n
≪ { } n + x SIZE + 0 CON
1 x SIZE '''FOR''' j
1 n '''FOR''' k
{ } k + j + x j GET k 1 - ^ PUT
'''NEXT NEXT'''
DUP y * SWAP DUP TRN * /
<span style="color:grey">@ the following lines convert the resulting vector into a polynomial equation</span>
DUP 'x' STO 1 GET
2 x SIZE '''FOR''' j 'X' * x j GET + '''NEXT'''
EXPAN COLCT
≫ ≫ '<span style="color:blue">FIT</span>' STO
 
[1 2 3 4 5 6 7 8 9 10] [1 6 17 34 57 86 121 162 209 262 321] 2 <span style="color:blue">FIT</span>
{{out}}
<pre>
1: '3+2*X+1*X^2'
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'matrix'
 
def regress x, y, degree
x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_fto_r } }
 
mx = Matrix[*x_data]
my = Matrix.column_vector(y)
 
((mx.t * mx).inv * mx.t * my).transpose.to_a[0].map(&:to_f)
end</langsyntaxhighlight>
'''Testing:'''
<syntaxhighlight lang ="ruby">betas =p regress ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321],
2)</syntaxhighlight>
 
p betas</lang>
{{out}}
<pre>[1.000000000000180, 2.000000000000110, 3.000000000000010]</pre>
 
=={{header|Scala}}==
{{Out}}See it yourself by running in your browser [https://scastie.scala-lang.org/NklZH2LlScCpfsN4NSfFvA Scastie (remote JVM)].
{{libheader|Scala Math Polynomial}}
{{libheader|Scastie qualified}}
{{works with|Scala|2.13}}
<syntaxhighlight lang="scala">object PolynomialRegression extends App {
private def xy = Seq(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321).zipWithIndex.map(_.swap)
 
private def polyRegression(xy: Seq[(Int, Int)]): Unit = {
val r = xy.indices
 
def average[U](ts: Iterable[U])(implicit num: Numeric[U]) = num.toDouble(ts.sum) / ts.size
 
def x3m: Double = average(r.map(a => a * a * a))
def x4m: Double = average(r.map(a => a * a * a * a))
def x2ym = xy.reduce((a, x) => (a._1 + x._1 * x._1 * x._2, 0))._1.toDouble / xy.size
def xym = xy.reduce((a, x) => (a._1 + x._1 * x._2, 0))._1.toDouble / xy.size
 
val x2m: Double = average(r.map(a => a * a))
val (xm, ym) = (average(xy.map(_._1)), average(xy.map(_._2)))
val (sxx, sxy) = (x2m - xm * xm, xym - xm * ym)
val sxx2: Double = x3m - xm * x2m
val sx2x2: Double = x4m - x2m * x2m
val sx2y: Double = x2ym - x2m * ym
val c: Double = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val b: Double = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
val a: Double = ym - b * xm - c * x2m
 
def abc(xx: Int) = a + b * xx + c * xx * xx
 
println(s"y = $a + ${b}x + ${c}x^2")
println(" Input Approximation")
println(" x y y1")
xy.foreach {el => println(f"${el._1}%2d ${el._2}%3d ${abc(el._1)}%5.1f")}
}
 
polyRegression(xy)
 
}</syntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Ruby}}
<syntaxhighlight lang="ruby">func regress(x, y, degree) {
<lang ruby>var Matrix = require('Math::Matrix')
var A = Matrix.build(x.len, degree+1, {|i,j|
x[i]**j
})
 
var B = Matrix.column_vector(y...)
func regress(x, y, degree) {
((A.transpose * A)**(-1) * A.transpose * B).transpose[0]
var x_data = x.map {|xi| (0..degree).map {|pow| xi**pow } }
}
 
var mx = Matrix.new(x_data...)
var my = Matrix.new(y.map{[_]}...)
 
func poly(x) {
mx.transpose.multiply(mx).invert.multiply(mx.transpose).multiply(my).transpose
3*x**2 + 2*x + 1
}
 
var betascoeff = regress(
10.of { _ },
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
10.of { poly(_) },
[1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321],
2
)
 
say coeff</syntaxhighlight>
betas.print</lang>
{{out}}
<pre>[1, 2, 3]</pre>
1.00000 2.00000 3.00000
</pre>
 
=={{header|Stata}}==
See '''[http://www.stata.com/help.cgi?fvvarlist Factor variables]''' in Stata help for explanations on the ''c.x##c.x'' syntax.
<langsyntaxhighlight lang="stata">. clear
. input x y
0 1
Line 1,463 ⟶ 2,432:
|
_cons | 1 . . . . .
------------------------------------------------------------------------------</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|Kotlin}}
<syntaxhighlight lang="swift">
 
let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
 
func average(_ input: [Int]) -> Int {
return input.reduce(0, +) / input.count
}
 
func polyRegression(x: [Int], y: [Int]) {
let xm = average(x)
let ym = average(y)
let x2m = average(x.map { $0 * $0 })
let x3m = average(x.map { $0 * $0 * $0 })
let x4m = average(x.map { $0 * $0 * $0 * $0 })
let xym = average(zip(x,y).map { $0 * $1 })
let x2ym = average(zip(x,y).map { $0 * $0 * $1 })
 
let sxx = x2m - xm * xm
let sxy = xym - xm * ym
let sxx2 = x3m - xm * x2m
let sx2x2 = x4m - x2m * x2m
let sx2y = x2ym - x2m * ym
let b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
let a = ym - b * xm - c * x2m
 
func abc(xx: Int) -> Int {
return (a + b * xx) + (c * xx * xx)
}
print("y = \(a) + \(b)x + \(c)x^2\n")
print(" Input Approximation")
print(" x y y1")
for i in 0 ..< x.count {
let result = Double(abc(xx: i))
print(String(format: "%2d %3d %5.1f", x[i], y[i], result))
}
}
 
polyRegression(x: x, y: y)
</syntaxhighlight>
 
{{out}}
<pre>
y = 1 + 2x + 3x^2
 
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0
</pre>
 
=={{header|Tcl}}==
Line 1,469 ⟶ 2,504:
<!-- This implementation from Emiliano Gavilan;
posted here with his explicit permission -->
<langsyntaxhighlight lang="tcl">package require math::linearalgebra
 
proc build.matrix {xvec degree} {
Line 1,517 ⟶ 2,552:
set coeffs [math::linearalgebra::solveGauss $A $b]
# show results
puts $coeffs</langsyntaxhighlight>
This will print:
1.0000000000000207 1.9999999999999958 3.0
which is a close approximation to the correct solution.
 
=={{header|TI-83 BASIC}}==
<syntaxhighlight lang="ti83b">DelVar X
seq(X,X,0,10) → L1
{1,6,17,34,57,86,121,162,209,262,321} → L2
QuadReg L1,L2</syntaxhighlight>
 
{{out}}
<pre>y=ax²+bx+c
a=3
b=2
c=1
</pre>
 
 
=={{header|TI-89 BASIC}}==
<langsyntaxhighlight lang="ti89b">DelVar x
seq(x,x,0,10) → xs
{1,6,17,34,57,86,121,162,209,262,321} → ys
QuadReg xs,ys
Disp regeq(x)</langsyntaxhighlight>
 
<code>seq(''expr'',''var'',''low'',''high'')</code> evaluates ''expr'' with ''var'' bound to integers from ''low'' to ''high'' and returns a list of the results. <code> →</code> is the assignment operator.
Line 1,545 ⟶ 2,594:
whereby the data can be passed as lists rather than arrays,
and all memory management is handled automatically.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import flo
 
(fit "n") ("x","y") = ..dgelsd\"y" (gang \/*pow float*x iota successor "n")* "x"</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">x = <0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.>
y = <1.,6.,17.,34.,57.,86.,121.,162.,209.,262.,321.>
 
#cast %eL
 
example = fit2(x,y)</langsyntaxhighlight>
{{out}}
<pre><3.000000e+00,2.000000e+00,1.000000e+00></pre>
 
=={{header|VBA}}==
Excel VBA has built in capability for line estimation.
<syntaxhighlight lang="vb">Option Base 1
Private Function polynomial_regression(y As Variant, x As Variant, degree As Integer) As Variant
Dim a() As Double
ReDim a(UBound(x), 2)
For i = 1 To UBound(x)
For j = 1 To degree
a(i, j) = x(i) ^ j
Next j
Next i
polynomial_regression = WorksheetFunction.LinEst(WorksheetFunction.Transpose(y), a, True, True)
End Function
Public Sub main()
x = [{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
y = [{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}]
result = polynomial_regression(y, x, 2)
Debug.Print "coefficients : ";
For i = UBound(result, 2) To 1 Step -1
Debug.Print Format(result(1, i), "0.#####"),
Next i
Debug.Print
Debug.Print "standard errors: ";
For i = UBound(result, 2) To 1 Step -1
Debug.Print Format(result(2, i), "0.#####"),
Next i
Debug.Print vbCrLf
Debug.Print "R^2 ="; result(3, 1)
Debug.Print "F ="; result(4, 1)
Debug.Print "Degrees of freedom:"; result(4, 2)
Debug.Print "Standard error of y estimate:"; result(3, 2)
End Sub</syntaxhighlight>{{out}}
<pre>coefficients : 1, 2, 3,
standard errors: 0, 0, 0,
 
R^2 = 1
F = 7,70461300500498E+31
Degrees of freedom: 8
Standard error of y estimate: 2,79482284961344E-14 </pre>
 
=={{header|Wren}}==
{{trans|REXX}}
{{libheader|Wren-math}}
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./math" for Nums
import "./seq" for Lst
import "./fmt" for Fmt
 
var polynomialRegression = Fn.new { |x, y|
var xm = Nums.mean(x)
var ym = Nums.mean(y)
var x2m = Nums.mean(x.map { |e| e * e })
var x3m = Nums.mean(x.map { |e| e * e * e })
var x4m = Nums.mean(x.map { |e| e * e * e * e })
var z = Lst.zip(x, y)
var xym = Nums.mean(z.map { |p| p[0] * p[1] })
var x2ym = Nums.mean(z.map { |p| p[0] * p[0] * p[1] })
 
var sxx = x2m - xm * xm
var sxy = xym - xm * ym
var sxx2 = x3m - xm * x2m
var sx2x2 = x4m - x2m * x2m
var sx2y = x2ym - x2m * ym
 
var b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
var c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2)
var a = ym - b * xm - c * x2m
 
var abc = Fn.new { |xx| a + b * xx + c * xx * xx }
 
System.print("y = %(a) + %(b)x + %(c)x^2\n")
System.print(" Input Approximation")
System.print(" x y y1")
for (p in z) Fmt.print("$2d $3d $5.1f", p[0], p[1], abc.call(p[0]))
}
 
var x = List.filled(11, 0)
for (i in 1..10) x[i] = i
var y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]
polynomialRegression.call(x, y)</syntaxhighlight>
 
{{out}}
<pre>
y = 1 + 2x + 3x^2
 
Input Approximation
x y y1
0 1 1.0
1 6 6.0
2 17 17.0
3 34 34.0
4 57 57.0
5 86 86.0
6 121 121.0
7 162 162.0
8 209 209.0
9 262 262.0
10 321 321.0
</pre>
 
=={{header|zkl}}==
Using the GNU Scientific Library
<langsyntaxhighlight lang="zkl">var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
xs:=GSL.VectorFromData(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
ys:=GSL.VectorFromData(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321);
Line 1,568 ⟶ 2,718:
v.format().println();
GSL.Helpers.polyString(v).println();
GSL.Helpers.polyEval(v,xs).format().println();</langsyntaxhighlight>
{{out}}
<pre>
Line 1,580 ⟶ 2,730:
 
Example:
<langsyntaxhighlight lang="zkl">polyfit(T(T(0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0)),
T(T(1.0,6.0,17.0,34.0,57.0,86.0,121.0,162.0,209.0,262.0,321.0)), 2)
.flatten().println();</langsyntaxhighlight>
{{out}}<pre>L(1,2,3)</pre>
2,442

edits