I'm trying to make a code for Gauss-Legendre quadrature. First I find the roots of the polyinomial with

roots[n_,x_]:=Solve[LegendreP[n, x] == 0]

Then I need to make $n$ functions which are products of $n-1$ terms, in the form of

$$ \prod_{\substack{j=1\\j\neq i}}^{n} \frac{x-x_j}{x_i-x_j} $$

with the $x_j$ being elements of roots[n,x], but I have to exclude $x_i$ in each function.

I tried this:

w[i_, x_] := Product[(x - roots[n, x][[j]])/(roots[n, x][[i]] - 
   roots[n, x][[j]]), {j, 1, n}, j!=i]

but I get an error Part specification j is neither an integer nor a list of integers. So now I have two concerns, is there a way to make a product (mind you, I need to make $n$ products for an arbitrary integer $n$) with skipping one iteration, and how do I use the results I get from Solve in the definition of w?


1 Answer 1


You can extract roots from a Solve command using the replacement operation /.:

xroots[n_]:= Solve[LegendreP[n, x] == 0]
roots[n_]:= x /. xroots[n]

Your Product call combined with an If condition, as suggested in the comment above, should do the trick.

w[i_, x_] := 
(x - roots[n][[j]])/(roots[n][[i]] - roots[n][[j]])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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