Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

python - Can't use the derivative function found with sympy.diff

I'm trying to use the derivative function found using sympy.diff to calculate other values. For some reason I get this message when I try my code:

ValueError: First variable cannot be a number: 4

Here is my code:

import sympy as sp

def f(x):
    return (x**2-3)/2

x = sp.Symbol('x')

def df(x):
    return sp.diff(f(x), x, 1)

print('la dérivée de f(x) est:', df(x))
print(df(4))
question from:https://stackoverflow.com/questions/66055141/cant-use-the-derivative-function-found-with-sympy-diff

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason is that in print(df(4)) you are passing the number 4 to df which passes it to sp.diff like sp.diff(f(4), 4, 1).

You meant to pass sp.Symbol('x') to sp.diff which then will return a function (= the derivative of f with respect to x) which to that you can pass the number 4 (= evaluate at x = 4).

import sympy as sp

def f(x):
    return (x**2-3)/2

x = sp.Symbol('x')

def df(x):
    return sp.diff(f(x), x, 1)

print('la dérivée de f(x) est:', df(x))
print(df(x)(4))  # note the additional (x) here

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...