Problem with scipy.optimize.newton(): "Add" object is not callable

Viewed 503

I'm writing a function that takes 2 lists and creates a polynomial function to later be solved by optimization.

I'm trying to create a string that looks like a function, convert it into a function by using sympy.sympify() and then pass it into optimize.newton().

However it keeps throwing a TypeError "Add" object is not callable while I already think that sympify has correctly returned a function.

I think I'm missing something very basic, maybe there is a function to turn my variable function0 into a function type for scipy to interpret correctly maybe?

def poly_build(coefficient_list, power_list):
    '''
    coefficient_list & power_list must be iterable objects of the same length, preferably a list
    '''
    if len (coefficient_list) != len(power_list):
        return False
    function = ""
    for n in range(0, len(coefficient_list)):
        if n != len(coefficient_list) - 1:
            function += f'{coefficient_list[n]}*x**{power_list[n]} +'
        else:
            function += f'{coefficient_list[n]}*x**{power_list[n]}'
    function0 = (sympy.sympify(function))
    function1 = sympy.diff(function0)
    function2 = sympy.diff(function1)

    return scipy.optimize.newton(function0, 1.5) 
1 Answers

A sympy function isn't a Python function as scipy.optimize.newton expects it. To convert:

pyfunction0 = sympy.lambdify(x, function0)
Related