I have searched online, and through this website, but the similar posts that create a function that evaluates the derivative of a function at x are not user input functions. For example, they will have f=2*x**2
, and I want to create a function that works for pretty much any function that contains algebraic operators, trig and log expressions, etc. I created a function that evaluates a user input function at x using numpy/math imports and eval(), but I can't quite replicate this for the derivative of a user input function.
from sympy import sympify, Symbol
import numpy
import math
x = Symbol('x')
y=sympify(input('Type your function:'))
yprime = y.diff(x)
I found this from a post online, and it accurately calculates the derivative of a user input function but I couldn't figure out how to add a function that evaluates yprime at some x value. When I tried to add
def fprime(x):
return eval(yprime, {'x': x, 'np': numpy, 'math': math})
I got an error that yprime is not a string, which it isn't.
TypeError: eval() arg 1 must be a string, bytes or code object
I would appreciate any help I can get, and note that I am a beginner with python.
You could try something like this:
from sympy import sympify, Symbol
import numpy
import math
x = Symbol('x')
y=sympify(input('Type your function:'))
value=float(input('Type the value to evaluate: '))
yprime = y.diff(x)
print(y)
print(yprime)
def fprime(value):
return float(yprime.subs({x:value}))
print(fprime(value))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.