0

I want to generate the Lagrange basis polynomials for a set of points where T is the set of points and n is the amount of given points. What I did is ci = [lambda t: np.prod([(t - T[j]) / (T[i] - T[j]) for j in range(n) if j != i] for i in range(n)], however, the resulting lambdas are all the same.

I checked by printing [c(val) for c in ci] in the console for several different values and it all returns the same value. How is this possible, when clearly the formula I put in should return lambdas with a different structure for each i?

  • 1
    There is only a single ``j`` variable which changes its value on each iteration. The lambdas refer to that ``j``, not to the-value-of-``j``-at-the-time-each-lambda-was-created. – MisterMiyagi Oct 17 '20 at 14:10
  • Thanks, that clears things up. Do you have an idea how to create the desired lambdas in a similarly short way? – J. Grünenwald Oct 17 '20 at 14:11
  • 1
    The simplest way is to capture the value as a default – defaults are evaluated at definition time, closures at calltime. In your case, that is ``lambda t, i=i: np.prod([(t - T[j]) / (T[i] - T[j])`` – this binds the current value of the outer ``i`` (from the loop) as the default value of the inner ``i`` (in the lambda). See the duplicates for details. – MisterMiyagi Oct 17 '20 at 14:13
  • I am unsure if I misread your comment, but that solved my problem now that I had a look at your comment again. Thanks for the help! – J. Grünenwald Oct 17 '20 at 14:21

0 Answers0