I am writing these recursion in python and don't get why the official solution is different than mine. The trivial cases for n = 1, 2 are clear. This is my approach:
return ((2*(k-1)-1)*x*leg(k-1) - ((k-1)-2)*leg(k-2)) / k
This is the official solution:
return ((2*k-1)*x*leg(k-1) - (k-1)*leg(k-2)) / k
Why are they decreasing k to call the function, but in the first part the coefficient (2*k-1) not? And why is the coefficient in the second part changed to (k-1)?
EDIT
So generally, afaiu, your issue stems from the formula (in your attached image does show L_{k+1}(x)
) while they do implement L_{k}(x)
without the intermediate derivation that shows how to obtain L_{k}(x)
from L_{k+1}(x)
.
I further think that there is some confusion here, so I will sightly deviate from the notation. Let m = k+1
in what follows.
We then obtain through straight forward substitution:
m * L(x, m) = (2*(m+1)-1) * x * L(x, m-1) - ((m-1)-2) * L(x, m-2) # for m >= 3
which yields
L(x, m) = ( (2*m + 2 - 1) * x * L(x, m-1) - ((m-3) * L(x, m-2) ) / m
and in python syntax, this is:
def L(x, m):
if m == 1:
return x
elif m == 2:
return 0.5 * (x**2 - 1)
else: # do this for all m >= 3
return ( (2*m + 1) * x * L(x, m-1) - ((m-3) * L(x, m-2) ) / m
Why are they decreasing k to call the function, but in the first part the coefficient (2*k-1) not?
IMHO they did, follow my derivation.
And why is the coefficient in the second part changed to (k-1)?
I honestly do not know; to me, it seems like they made a mistake during substitution, ie they must have put m+1
instead of m-1
.
>>> (2*(k-1)-1)
Does first compute k-1
multiplies it by 2
and then subtracts 1
which is indifferent from 2*k-1
. For example:
k = 5
does yield with your solution (2*(5-1)-1) = 7
and from the official solution (2*5-1) = 9
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.