Suppose I have a polynomial f(x) where all the coefficients a(i) are integers in the form of a function f, implement a function find_polynomial that takes f and returns the coefficients a(i) as a list of the form:
[a(0),a[1]....a[n]] (n<=15)
where a[n] is the last non-zero coefficient of f(x). The only other information about f(x) is that it is of finite degree (<=15). And the solution shall not import any module.
My approach was to try using the Lagrange polynomial, which is a more mathematical method of solving the solution, but it will not work for coefficient bigger than 10 ** 10), so I would like to know a much more stable solution which can solve all the unknown coefficients. Would like to see the passion for community to solve hard problems. Any help is welcomed :)
Unknown Functions:
def f(x):
return 5 * x**3
def g(x):
return 6 * x**6 - 2 * x**5 + 3*x + 5 * x**3
def h(x):
return 5 + 3 * x**2 - 2 * x**11 + x + 3 * x**15
def z(x):
return 5 + 3 * x**2 - 2 * x**11 + x + 3 * x**15-2*x**8
def p(x):
return 5 + 3 * x**2 -31 * x**10 + x + 3 * x**15+13*x**8+14*x**9
def wrong(x):
return 5 + 3 * x**2 -1 * x**10 + x + 10000000000 * x**15+13*x**8+14*x**9
Test Case:
print(find_polynomial(f))
print(find_polynomial(g))
print(find_polynomial(h))
print(find_polynomial(z))
print(find_polynomial(p))
print(find_polynomial(wrong))
Result:
(0, 0, 0, 5)
(0, 3, 0, 5, 0, -2, 6)
(5, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, 0, 0, 3)
(5, 1, 3, 0, 0, 0, 0, 0, -2, 0, 0, -2, 0, 0, 0, 3)
(5, 1, 3, 0, 0, 0, 0, 0, 13, 14, -31, 0, 0, 0, 0, 3)
'''This ouput is wrong''' (5, 348713164801, -1133862589437, 1568627191296, -1243957041600, 638886422720, -226653467040, 57637291712, -10725815087, 1473646474, -149249101, 10998988, -573300, 20020, -420, 10000000004)
My approach:
def fact(num):
if num==0:
return 1
else:
return num*fact(num-1)
def poly(x):
result=[]
for i in range(x+1):
y=fact(i)*fact(x-i)*((-1)**(x-i))
result.append(y)
return result
def find_polynomial(func):
result=[0]*16
def helper(len1,func,result):
if len1==0 or func(1)==0:
result[15-len1]=func(0)
return result
else:
sum1=0
polyx=poly(len1)
for i in range(len1+1):
j=(func(i)/polyx[i])
sum1+=j
result[15-len1]=int(round(sum1))
return helper(len1-1,lambda x:func(x)-result[15-len1]*(x**len1),result)
lst1=helper(15,func,result)
def finalize(lst):
if lst[0]!=0:
return tuple(reversed(lst))
else:
return finalize(lst[1:])
return finalize(lst1)