简体   繁体   中英

Python scipy module derivate not working with input from user

When I tried to calculate a derivate from an user it gave me an error, that says that derivate does not take string inputs, but so how Ican achieve this

import scipy.misc import derivate

fx=input()
print(derivative(fx,1.0,dx=1e-8))

The first parameter is func , not str docs . If you want it as input you can use lambda and eval . The input need to be in x**3 + x**2 format

fx = input()
f = lambda x: eval(fx)

print(derivative(f, 1.0, dx=1e-8))

Use below code

from scipy.misc import derivative

def f(x):
   return x**2 + x
print(derivative(f,1.0,dx=1e-6))

------------ Updated---------------------

Explanation: - With your code you have tried to pass a string to the function derivative which expects a function instead , here is the doc

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM