我一直在尝试为单个变量的功能获取最小值。该函数是:
sym.sqrt((x+6)**2 + 25) + sym.sqrt((x-6)**2 - 121)
函数的导数(是(x-6)/sym.sqrt((x-6)** 2-121)+(x + 6)/sym.sqrt((x + 6)** 2 + 25))爆破x等于-5,由于第一项,如果x大于-5(例如-4)但小于18(我们在此为简单起见,可以忽略),广告变得复杂。因此,我编写了代码,仅对-6和-10之间的x求函数(通过检查,我可以看到最小值约为-8.6,所以我选择-10):
def h(x):
for x in np.arange(-10,-5):
sym.sqrt((x+6)**2 + 25) + sym.sqrt((x-6)**2 - 121)
result = optimize.minimize_scalar(h,bounds=(-10,-5))
x_min = result.x
print(x_min)
不幸的是,我收到此错误:
TypeError:输入类型不支持ufunc'isnan',并且根据强制转换规则“ safe”,不能将输入安全地强制转换为任何受支持的类型
有人可以帮助我解决这个问题吗?
关于
普拉桑那
答案 0 :(得分:0)
除非您lambdify
保持sympy公式,否则我认为numpy和sympy不能很好地配合使用。而且我也不确定NaN
的值,这些值似乎在您的方程式中。
您可以尝试数字方式。在绘制函数时,我发现该范围内没有最小值,但是导数中有最大值:
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import argrelmax
x = np.linspace(-10, -6, 256) # generate x range of interest
y = np.sqrt((x+6)**2 + 25) + np.sqrt((x-6)**2 - 121)
dydx = (x - 6)/np.sqrt((x - 6)**2 - 121) + (x + 6)/np.sqrt((x + 6)**2 + 25)
maximum, = argrelmax(dydx) # returns index of maximum
x[maximum]
>>> -8.50980392
# plot it
plt.plot(x, y)
ax = plt.gca().twinx() # make twin axes so can see both y and dydx
ax.plot(x, dydx, 'tab:orange')
ax.plot(x[maximum], dydx[maximum], 'r.')