'Input a function and calculate derivative in python
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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eli Harold |
