我如何区分下一段代码:
import sympy as sp
x = sp.symbols('x')
fx = sp.lambdify(x, -x**2-8*x-sp.sqrt(10 * x))
df = sp.diff(fx(x))
我怎么能用符号或者别的什么东西?
AttributeError Traceback (most recent call last)
AttributeError: 'Symbol' object has no attribute 'sqrt'
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
Input In [110], in <cell line: 4>()
2 x = sp.symbols('x')
3 fx = sp.lambdify(x, -x**2-8*x-sp.sqrt(10 * x))
----> 4 df = sp.diff(fx(x))
File <lambdifygenerated-85>:2, in _lambdifygenerated(x)
1 def _lambdifygenerated(x):
----> 2 return -sqrt(10)*sqrt(x) - x**2 - 8*x
TypeError: loop of ufunc does not support argument 0 of type Symbol which has no callable sqrt method
发布于 2022-04-19 22:25:04
这里是获得差异化的正确方法
x = sp.symbols('x')
expr = -x**2-8*x-sp.sqrt(10 * x)
fx = sp.lambdify(x, expr.diff(x))
输出:
-2*x - 8 - sqrt(10)/(2*sqrt(x))
发布于 2022-04-20 00:28:41
来说明我的意见。使用跟踪中所示的代码创建一个函数:
In [20]: def foo(x):
...: return -np.sqrt(10)*np.sqrt(x) - x**2 - 8*x
...:
它可以很好地处理标量数组或数字数组:
In [21]: foo(1)
Out[21]: -12.16227766016838
In [22]: foo(np.arange(3))
Out[22]: array([ -0. , -12.16227766, -24.47213595])
但是,当给定一个sympy.symbol
时,它会引发以下错误:
In [23]: x
Out[23]: x
In [24]: foo(x)
AttributeError: 'Symbol' object has no attribute 'sqrt'
numpy
函数(如np.sqrt
)首先将它们的输入转换为数组:
In [1]: np.array(x)
Out[1]: array(x, dtype=object)
然后尝试执行x.sqrt()
,这就产生了AttributeError
。
https://stackoverflow.com/questions/71931656
复制相似问题