Polynomial regression: Difference between revisions

(→‎{{header|Raku}}: note about the rationale written in French)
 
(3 intermediate revisions by 2 users not shown)
Line 1,358:
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 2,106 ⟶ 2,182:
 
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>
Line 2,128 ⟶ 2,204:
\end{align}</math>
 
<syntaxhighlight lang="raku" line>use CliffordMultiVector;
 
constant @x1 = <0 1 2 3 4 5 6 7 8 9 10>;
Line 2,578 ⟶ 2,654:
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./math" for Nums
import "./seq" for Lst
import "./fmt" for Fmt
 
var polynomialRegression = Fn.new { |x, y|
2,442

edits