-2

I want to ask a user to enter a function:

function = input('Input expression: ') # x**2 + 1 or cos(x)

I want to be able to evaluate this function, for example f(1). I want to compute the derivative f', such that again, i can do f'(0) for example. There are several ways to do this, but I also need to calculate the derivative f' and be able to evaluate it as well, e.g. f'(0). I do not know how to do so that from an expression (string) I can evaluate it, calculate its derivative and also be able to evaluate it.

didiegop
  • 139
  • 3
  • if you enter a valid python expression you can use `eval` or even better `ast.literal_eval`. Something like "4 + 2" will evaluate to 6. What result do expect when you enter `x**2+1` or `cos(x)` since you are not giving any value for x. –  Feb 01 '22 at 15:17
  • @SembeiNorimaki Yes, I used eval but I don't know how to compute the derivate from eval. – didiegop Feb 01 '22 at 15:20
  • put in your question an example of input and the expected output. So you want your program to calculate the derivative of an expression? so the string "cos(x)" should return the string "sin(x)"? It's unclear what you want –  Feb 01 '22 at 15:21

1 Answers1

0

You can use a method like this for x**2 + 1:

from sympy import *
import numpy as np
x = Symbol('x')
y = x**2 + 1
yprime = y.diff(x)
print(yprime)

Ouput:

2x

for cos() you could use something like this:

from scipy.misc import derivative
import math
def f(x):
  return math.cos(x)

y1 = derivative(f,5.0,dx=1e-9)
Eli Harold
  • 2,280
  • 1
  • 3
  • 22