Search code examples
pythonnumpymathsympysymbolic-math

Finding a function that fits several arguments


I want to find a sympy function, that fulfills several arguments. It should go through several points and have a certain derivative at some points. How do I do that?

values = np.array([1.0, 2.0], [2.0, 3.0])
derivats = np.array([1.0, 3.0], [2.0, 5.0])

Please help me and my mathematical English is not that good, so please use words that I can google.


Solution

  • Here is a interpretation with SymPy's solve (docs) and polynomials, to give an idea of the possibilities:

    from sympy import *
    
    x = symbols('x', real=True)
    n = 4  # degree of the polynomial
    a = [symbols('a%d' % i, real=True) for i in range(n)]
    print(a)
    f = sum([a[i]*x**i for i in range(n)])  # f is a polynomial of degree n
    g = f.diff(x)
    sol = solve([Eq(f.subs(x, 1), 2), Eq(f.subs(x, 2), 3), Eq(g.subs(x, 1), 3), Eq(g.subs(x, 2), 5), ], a)
    print(sol)
    print(f.subs(sol))
    

    This prints:

    {a0: -15, a1: 37, a2: -26, a3: 6}
    6*x**3 - 26*x**2 + 37*x - 15
    

    Directly working with your arrays, this could be:

    from sympy import *
    
    x = symbols('x', real=True)
    n = 4  # degree of the polynomial
    a = [symbols('a%d' % i, real=True) for i in range(n)]
    f = sum([a[i]*x**i for i in range(n)])  # f is a polynomial of degree n
    g = f.diff(x)
    values = [[1.0, 2.0], [2.0, 3.0]] # suppose an array of pairs [x, f(x)]
    derivats = [[1.0, 3.0], [2.0, 5.0]]  # suppose an array of pairs [x, f'(x)]
    equations = [Eq(f.subs(x, xi), yi) for xi, yi in values] + [Eq(g.subs(x, xi), yi) for xi, yi in derivats]
    sol = solve(equations)
    print(sol)
    print(f.subs(sol))
    

    This outputs:

    {a0: -15.0000000000000, a1: 37.0000000000000, a2: -26.0000000000000, a3: 6.00000000000000}
    6.0*x**3 - 26.0*x**2 + 37.0*x - 15.0
    

    Note that SymPy is less happy to work with reals than with integers and fractions.