如何在Python中进行非线性复根搜索

2024-04-29 10:57:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想对下面的非线性方程做根搜索,我用Python做的,但是没有用。我的代码如下

from pylab import *
import scipy
import scipy.optimize

def z1(x,y):
    temp=1+1j+x+2*y;
    return temp

def z2(x,y):
    temp=-1j-2*x+sqrt(3)*y;
    return temp

def func(x):
    temp=[z1(x[0],x[1])-1.0/(1-1.0/(z2(x[0],x[1]))),1-2.0/(z2(x[0],x[1])-4.0/z1(x[0],x[1]))]
    return temp

result=scipy.optimize.fsolve(func,[1+1j,1+1j])

print result

当我运行它时,它显示错误:

--->;30 result=scipy.optimize.fsolve(函数,[1+1j,1+1j])

C:\ Python27\lib\site packages\scipy\optimize\minpack.py,在fsolve中(func,x0,args,fprime,full_output,col椆deriv,xtol,maxfev,band,epsfcn,factor,diag)

123             maxfev = 200*(n + 1)

124         retval = _minpack._hybrd(func, x0, args, full_output, xtol,

-->;125最大值,ml,mu,epsfcn,因子,diag)

126     else:

127         _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n,n))

Tags: importgtreturndefargsscipyresulttemp
2条回答

fsolve从R^n->;R中查找函数的零。类似的函数^{}从R^n->;R^m中查找函数的零

看起来你在试图从C^2->;C^2中找到一个函数的零,据我所知,scipy.optimize不直接支持这个功能,但是你可以尝试从R^4->;R^4中编写一个函数,然后使用root。例如,大致如下:

def func_as_reals(x):
    r1, c1, r2, c2 = x
    a, b = func([complex(r1, c1), complex(r2, c2)])
    return [a.real, a.imag, b.real, b.imag]

应该可以工作,尽管直接对实数执行可能要快得多,而不是重复包装成复杂的展开。

你可以试试mpmath的findroot(sympy):

from mpmath import findroot

#Your code here

ans = findroot([z1,z2],(0,0))
print(ans)

返回:

[(-0.302169479251962 - 0.651084739625981j)]
[(-0.348915260374019 - 0.174457630187009j)]

这是您系统的解决方案。
Mpmath是一个多精度库,所以它的例程通常比较慢,但是您可以尝试一下!

相关问题 更多 >