The Null
appears because two-argument If[]
produces Null
if the condition in the first argument is not satisfied. Αλέξανδρος shows one possibility, but you can fix your original code by recalling that $1$ is the identity element for multiplication; thus, you can implement Lagrangian interpolation like so:
With[{x1 = {1, 2, 3, 4}, y1 = {3, 4, 2, 5}},
p1 = Sum[Indexed[y1, i]
Product[If[i != j, (x - Indexed[x1, j])/(Indexed[x1, i] - Indexed[x1, j]), 1],
{j, 1, Length[x1]}], {i, 1, Length[x1]}]];
Check:
Simplify[p1 == InterpolatingPolynomial[Transpose[{{1, 2, 3, 4}, {3, 4, 2, 5}}], x]]
True
That being said, the classical version is not the best way to implement Lagrangian interpolation; in particular, one might consider instead using the so-called barycentric form:
With[{x1 = {1, 2, 3, 4}, y1 = {3, 4, 2, 5}},
w = Table[1/Apply[Times, x1[[j]] - Delete[x1, j]], {j, 1, Length[x1]}];
p2 = (w/(x - x1)).y1/Total[w/(x - x1)]];
Check:
Simplify[p2 == InterpolatingPolynomial[Transpose[{{1, 2, 3, 4}, {3, 4, 2, 5}}], x]]
True
See the linked paper for more details.
If
(If[ j != i, result1, result2]
). With two-argument formIf[j!=i,result]
,If
returnsNull
whenj==i
. $\endgroup$ – kglr Sep 5 '19 at 4:42Product[If[j!=i,term,1]...]
which will insert either the term or a 1 into your product. And you can use the same trick using a zero when you are doing sums instead of products. $\endgroup$ – Bill Sep 5 '19 at 4:47