首页 > 解决方案 > odeint:无法根据规则“安全”将数组数据从 dtype('complex128') 转换为 dtype('float64')

问题描述

以下代码给出了错误:Cannot cast array data from dtype('complex128') to dtype('float64') based on the rule 'safe'

import numpy as np
from numpy.fft import fft
from scipy.integrate import odeint

t = np.linspace(0,9,10)

def func(y, t):
    k = 0
    dydt = fft(y)
    return dydt

y0 = 0
y = odeint(func, y0, t)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-4885da912033> in <module>
     10 
     11 y0 = 0
---> 12 y = odeint(func, y0, t)

~\AppData\Local\Continuum\anaconda3\envs\udacityDL\lib\site-packages\scipy\integrate\odepack.py in odeint(func, y0, t, args, Dfun, col_deriv, full_output, ml, mu, rtol, atol, tcrit, h0, hmax, hmin, ixpr, mxstep, mxhnil, mxordn, mxords, printmessg, tfirst)
    243                              full_output, rtol, atol, tcrit, h0, hmax, hmin,
    244                              ixpr, mxstep, mxhnil, mxordn, mxords,
--> 245                              int(bool(tfirst)))
    246     if output[-1] < 0:
    247         warning_msg = _msgs[output[-1]] + " Run with full_output = 1 to get quantitative information."

TypeError: Cannot cast array data from dtype('complex128') to dtype('float64') according to the rule 'safe'

但是,如果我从以下位置返回真实值(而不是复杂值)func

def func(y, t):
    k = 0
    dydt = fft(y)
    return np.abs(dydt)

然后odeint工作没有任何错误。

谁能帮我确定/解决这个问题的根源?

提前致谢!

标签: pythonscipydifferential-equationsodeintode45

解决方案


您正在更改数据类型并返回复数值,而 ODE 求解器需要实数值。

你也可以试着让你的输入变得复杂,这样至少这一点不会产生矛盾

y0 = 0+0j

您到底期望什么作为解决方案?在任何合理的解释中,您都会得到零函数。


推荐阅读