# Smoother ways for setting up a Product function with j=0 and j != i

I want to implement a Product function, particularly the Lagrange polynomial

$$\ell_{i}(x)=\prod_{j=0 \atop j \neq i}^{n} \frac{x-x_{j}}{x_{i}-x_{j}}$$

Are there ways to implement the "not equal" other than with an If statement?

New contributor
Rapiz is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Just for fun, here all functions $$l$$ in one go as a vector l:

n = 4;
X = Array[x, n];
id = IdentityMatrix[n];
l = Times @@ Divide[
Outer[Plus, -X, ConstantArray[x, n]] (1 - id) + id,
Outer[Plus, -X, X] + id
]


You can always directly supply an edited index list to Product[]:

With[{n = 5, i = 3},
Product[(x - \[FormalX][j])/(\[FormalX][i] - \[FormalX][j]),
{j, DeleteCases[Range[0, n], i]}]]
((x - x[0]) (x - x[1]) (x - x[2]) (x - x[4]) (x - x[5]))/
((-x[0] + x[3]) (-x[1] + x[3]) (-x[2] + x[3]) (x[3] - x[4]) (x[3] - x[5]))


(formal variables edited for clarity)

• Or else {j,Complement[Range[0,n],{i}]}, or also {j,Union[Range[0,i-1],Range[i+1,n]]} – მამუკა ჯიბლაძე Dec 3 at 17:23
With[{n = 4, i = 3},
InterpolatingPolynomial[
Transpose[{Array[x, n + 1, 0],
SparseArray[i + 1 -> 1, n + 1]}], y] // FullSimplify]

(*     (((y-x[0])(y-x[1])(y-x[2])(y-x[4]))/((x[3]-x[0])(x[3]-x[1])(x[3]-x[2])(x[3]-x[4])))    *)

• For readability, I'd suggest Table[{x[j], KroneckerDelta[j, i]}, {j, 0, n, 1}] to generate your input for InterpolatingPolynomial (+1). – MarcoB Dec 2 at 22:15
• I agree, thanks @MarcoB for for cleaning this up. – Roman Dec 3 at 8:04