0
def fun(z):
    g = np.zeros(4 * N)
    for i in range(4 * N):
        f = np.zeros(4 * N)
        for j in range(4 * N):
            f[i] = f[i] + M_kk[i][j] * z[j] * np.arcsinh(w_c / z[j])
            g[i] = f[i] - z[i]
    return(g)
z = fsolve(fun, dk)

When solving the equation, it reports the error: Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'. How can I solve this issue?

ComplexWarning: Casting complex values to real discards the imaginary part
  f[i] = f[i] + M_kk[i][j] * z[j] * np.arcsinh(w_c / z[j])

ComplexWarning: Casting complex values to real discards the imaginary part
  g[i] = f[i] - z[i]

Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python310\Lib\site-packages\simple test.py", line 112, in <module>
    z = fsolve(fun, dk)

  File "C:\Users\AppData\Local\Programs\Python\Python310\Lib\site-packages\scipy\optimize\_minpack_py.py", line 160, in fsolve
    res = _root_hybr(func, x0, args, jac=fprime, **options)

  File "C:\Users\AppData\Local\Programs\Python\Python310\Lib\site-packages\scipy\optimize\_minpack_py.py", line 237, in _root_hybr
    retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev,
TypeError: Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • My guess is that your `arcsinh` is producing complex values. If so then the `g` and `f` arrays need to be created with a `complex` dtype. But you really should show the full error traceback. – hpaulj Sep 28 '22 at 16:20
  • ComplexWarning: Casting complex values to real discards the imaginary part f[i] = f[i] + M_kk[i][j] * z[j] * np.arcsinh(w_c / z[j]) – karren lim Sep 28 '22 at 16:24
  • I'm not sure from the traceback whether the assignments in your function just produce the warning or raise the error. It almost looks like the error is produced in the `fsolve` part, where it does something like `np.array(result, dtype=float)`. Do you really expect complex values in this calculation? If not, you need to figure out where they come from. I suspect `arcsinh`, but haven't used it much, so can say for sure. – hpaulj Sep 28 '22 at 16:41

0 Answers0