应用导数而不是输入导数
在此代码中,函数及其导数旨在输入,因为 Eval 接受字符串:
def newton(func, deriv, x, n):
def f(x):
f =eval(func)
return f
def df(x):
df =eval(deriv)
return df
for h in range(1,n):
i = x - (f(x)/df(x))
x = i
但是,如果我们希望机器向我们建议导数,使输入如下所示,该怎么办?
newton(str(y),str(y.diff), 2,10)
输出是“x* 的绑定方法 Expr.diff” *2 + 1 英寸。有办法解决这个问题吗?谢谢。
In this code, function and its derivative are intended to be type in, since Eval accepts strings:
def newton(func, deriv, x, n):
def f(x):
f =eval(func)
return f
def df(x):
df =eval(deriv)
return df
for h in range(1,n):
i = x - (f(x)/df(x))
x = i
But what if we wish the machine to advise us the derivative, making the input like:
newton(str(y),str(y.diff), 2,10)
The output is "bound method Expr.diff of x**2 + 1". Is the a way to fix this? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字符串不知道如何计算导数,但是(如果您确实想这样做)您需要一个字符串来表示字符串 y 所描述的函数的导数。因此,创建一个知道如何求导数的 SymPy 对象,求导数,然后将其转换回字符串:(
但是,如果没有 return 语句,您的函数将不会向您显示任何内容。)
Strings don't know how to calculate a derivative but (if you really want to do it this way) you need a string that represents the derivative of the function described by the string
y
. So create a SymPy object that knows how to take the derivative, take the derivative, then convert it back to a string:(Your function won't show you anything, however, without a return statement.)