2
$\begingroup$

I'm trying to solve for the Lagrangian form of the interpolation polynomial. Right now, I'm just trying to solve for the $l_i(x)$ values which are equal to $l_i(x)=\prod_{j\neq i, j=1}^{n}{\frac{x-x_j}{x_i-x_j}} $. Where $n$ is the length of the list of x values. My code right now is:

LagrangeL[i_, xList_] := 
 Product[(x - xList[j])/(xList[i] - xList[j]) Boole[i != j], {j, 1, 
   Length[xList]}]

This is giving me $Indeterminate$ for $LagrangeL[1, \left\{1, 2\right\}]$ and I'm not sure why. Is there a way to make the condition of $j \neq i$ in the product index?

$\endgroup$
3
$\begingroup$

Two problems: your xList is a List, so index into it with [[ ]] rather than [ ], and you need to keep the denominator from evaluating.

LagrangeL[i_, xList_] := Product[If[i != j, 
   (x - xList[[j]])/(xList[[i]] - xList[[j]]), 1], {j, 1, Length[xList]}] 

2 - x
$\endgroup$
  • $\begingroup$ Thank you, that worked. One more question now, am I able to set a new function equal to the output of this? So like f[x_]:=LagrangeL[1,{1,2}]; f[0]. $\endgroup$ – TheStrangeQuark Sep 16 '16 at 14:58
  • 1
    $\begingroup$ Sure -- the output is a polynomial, so you can work with it as with any polynomial. But what you probablby want is: f[x_] = LagrangeL[1, {1, 2}] so that you can have f[0]=2, f[2]=0, etc. $\endgroup$ – bill s Sep 16 '16 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.