0

I have been trying to get the minimum for a function of a single variable. The function is:

sym.sqrt((x+6)**2 + 25) + sym.sqrt((x-6)**2 - 121)

The function's derivative (which is (x - 6)/sym.sqrt((x - 6)**2 - 121) + (x + 6)/sym.sqrt((x + 6)**2 + 25)) blows up for x equal to -5 ad becomes complex for x greater than that (for example, -4) but less than 18 (which we can ignore for simplicity here), due to the first term. Therefore, I wrote the code to only evaluate the function for x between -6 and -10 (by inspection, I could see that the minimum was around -8.6, so I chose -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)

Unfortunately, I got this error:

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

Can someone help me with this issue?

Regards,

Prasannaa

4

1 回答 1

0

我不认为 numpy 和 sympy 一起玩得很好,除非你lambdify的 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.')

上面的代码图,最大标识

于 2020-04-28T16:44:48.587 回答