Lagrange Interpolation: Difference between revisions

m (→‎{{header|Wren}}: Changed to Wren S/H)
Line 36:
 
(The J representation of a polynomial is the list of coefficients of the polynomial such that the index of the coefficient is the power applied to the polynomial's variable.)
 
=={{header|jq}}==
{{works with|jq}}
 
'''Works with gojq, the Go implementation of jq'''
 
'''With minor modifications related to the module system, the program presented here also works with jaq, the Rust implementation of jq'''
 
'''The function `lagrange/1` is adapted from [[#Wren|Wren]].'''
 
This entry uses the [[:Category:jq/polynomials.jq|"polynomials" module]] in which a polynomial is
represented by the JSON array comprised of the polynomial's
coefficients, with the entry at .[i] corresponding to the coefficient
of x^i. The canonical form of a polynomial of degree n is represented
by an array of length n+1.
<syntaxhighlight lang="jq">
include "polynomials" {search: "./"};
 
# Returns the Lagrange interpolating polynomial which passes through a list of points.
def lagrange($pts):
($pts|length) as $c
| reduce range(0;$c) as $i ({polys: []};
.poly = [1]
| reduce range(0;$c) as $j (.;
if ($i != $j)
then .poly = (multiply(.poly; [-$pts[$j][0], 1]))
else .
end )
| (.poly | eval($pts[$i][0])) as $d
| .polys[$i] = (.poly | scalarDivide($d)) )
| reduce range(0;$c) as $i (.sum = [0];
.polys[$i] = (.polys[$i] | scalarMultiply($pts[$i][1]))
| .sum = add(.sum; .polys[$i]) )
| .sum ;
 
def pts: [
[1, 1],
[2, 4],
[3, 1],
[4, 5]
];
 
lagrange(pts) | pp
<syntaxhighlight>
'''Output'''
{output}
<pre>
2.1666666666666665x³-16.0x²+35.83333333333333x-21.0
</pre>
 
=={{header|Julia}}==
2,459

edits