Search code examples
pythonmathderivative

Derivative On Python


Hi I make some derivative Program on Python, but the result isn't same as what i expected,

This is the result as what i want to be :

f(x) = x^2 - 8x + 25
f'(x) = 2x -8
    0 = 2x - 8
    8 = 2x
    4 = x
    x = 4

i want x to be equal to 4

and here's the code :

import sympy as sp     

from sympy import *

p = 8
m = 25

f = x**2 - p*x + m
f_prime = f.diff(x)

f = lambdify(x, f) 
f_prime = lambdify(x, f_prime)

f_prime(2)

the result is -4

how to solve this problem?

Thankyou


Solution

  • You have to define x as a symbolic variable (otherwise code will not compile), lambdify f_prime and solve the equation f_prime(x) = 0

    from sympy import *
    
    p = 8
    m = 25
    
    x = symbols('x')
    
    f = x**2 - p*x + m
    f_prime = f.diff(x)
    print (f_prime)
    
    f_prime = lambdify(x, f_prime)
    print(solve(f_prime(x))[0])
    
    2*x - 8
    4