3
$\begingroup$

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.
$\endgroup$
  • 2
    $\begingroup$ Define the function as the product of two Products $\endgroup$ – Bob Hanlon Dec 2 at 17:56
  • $\begingroup$ Have you seen InterpolatingPolynomial? $\endgroup$ – Roman Dec 2 at 19:59
6
$\begingroup$

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
   ]
$\endgroup$
6
$\begingroup$

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)

$\endgroup$
5
$\begingroup$

Using InterpolatingPolynomial:

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])))    *)
$\endgroup$
  • 1
    $\begingroup$ For readability, I'd suggest Table[{x[j], KroneckerDelta[j, i]}, {j, 0, n, 1}] to generate your input for InterpolatingPolynomial (+1). $\endgroup$ – MarcoB Dec 2 at 22:15
  • $\begingroup$ I agree, thanks @MarcoB for for cleaning this up. $\endgroup$ – Roman Dec 3 at 8:04

Your Answer

Rapiz is a new contributor. Be nice, and check out our Code of Conduct.

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.