Search code examples
pythonsympyderivative

Difference between defining a function inside versus outside of another function


I have written a function derivative(w1, w2, pt) that evaluates the derivative of the function f(x) = w1 * x**3 + w2 * x - 1 at point pt. Strangely, I have found that I get different results depending on whether def f(x) is positioned inside or outside of derivative(w1, w2, pt). Why does the positioning of def f(x) matter / which is correct?

Example 1:

def derivative(w1, w2, pt):
    x = sy.Symbol('x')

    def f(x):
        return w1 * x**3 + w2 * x - 1

    # Get derivative of f(x)
    def df(x):
        return sy.diff(f(x),x)

    # Evaluate at point x
    return df(x).subs(x,pt)   

From which derivative(5, 8, 2) returns 68.

Example 2:

def f(x):
    return w1 * x**3 + w2 * x - 1

def derivative(w1, w2, pt):
    x = sy.Symbol('x')

    # Get derivative of f(x)
    def df(x):
        return sy.diff(f(x),x)

    # Evaluate at point x
    return df(x).subs(x,pt)

From which derivative(5, 8, 2) returns 53.


Solution

  • I think it's your global scope that is polluted. Look at this example :

    import sympy as sy
    
    def f(x, w1, w2):
        return w1 * x**3 + w2 * x - 1
    
    def derivative(w1, w2, pt):
        x = sy.Symbol('x')
    
        # Get derivative of f(x)
        def df(x, w1, w2):
            return sy.diff(f(x, w1, w2),x)
    
        # Evaluate at point x
        return df(x, w1, w2).subs(x,pt)
    
    print(derivative(5, 8, 2))
    

    This is just a modified version of your example 2 and it returns the same answer.