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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...