1
votes

Currently i'm stuck in finding the lagrange polynomial Li function's derivative. This is how i write the Li function :

def Li(x, xArr, n):
  L = 1
  resArr = []
  for i in range(n):
    for j in range(n):        
      if j == i:          
        continue
      L = L * ((x - xArr[j])/ (xArr[i] - xArr[j]))
    resArr.append(round(L,4))
    L = 1
  return resArr

And i want to calculate the derivatives of the array results from the function. For example, if we try to hardcode it, with a given xArr = [10.5, 12] it will look like :

L[0] = (x - xArr[1]) / (xArr[0] - xArr[1]) * (x- xArr[0]) / (xArr[1] - xArr[0])
L[0] = (x - 12)/(10.5 - 12) * (x - 10.5)/(12 - 10.5)
L[0] = (x^2 - 22.5x + 126) / -2.25

and then we'll find the derivative of L[0] with that function (x^2 - 22.5x + 126) / -2.25, in manual solving, we can insert the x later, but if we code it, i assume that the code must know the x value first, right?

so, for example i give the x value = 11.5, and it makes the results of L[0] = 0.3333

and now i want to calculate the derivative of L[0] and the result will be :

L'[0] = 2x - 22.5 / -2.25 for x = 11.5
L'[0] = 0.5

Is there any ways to do so? I've tried using torch.tensor, and using np.diff, but the results is not satisfying. Thank you.

1
add more details to your question, explain what you are expecting etc...ombk

1 Answers

1
votes

It is not entirely clear what you want so more details per comment from @ombk would be helpful, but if you want a numerical derivative of your function you can do it like this. Note we use numpy for arithmetic operations on arrays as basic lists do not work like that

import numpy as np
eps = 0.1
L_base = Li(11.5, [10.5, 12], 2)
L_bumped = Li(11.5+eps, [10.5, 12], 2)
derivs = (np.array(L_bumped) - np.array(L_base))/eps
derivs

Here we bump x by a small amount, recalculate yourfunction and see the rate of change (which is the definition of first derivative)

The code produces

array([-0.666,  0.666])

these are (numerical) derivatives of L[0] and L[1] with respect to x at x=11.5

A few comments. Why do you do round(L,4) in your code? It is nice for printing out the results but does not work for numerical calculations as you lose precision. especially with derivatives, setting eps to 1e-4 in the code above does not work because the result gets rounded off

Also your 'by hand' example is wrong, and inconsistent with your code. For xArr of two elements, 'Li' functions are linear so it should be

L[0] = (x - xArr[1]) / (xArr[0] - xArr[1]) 
L[1] = (x- xArr[0]) / (xArr[1] - xArr[0])

finally you do not need n as one of the function arguments as you can just calculate it from the list xArr, n=len(xArr)