Python fsolve()抱怨形状。为什么?

时间:2014-02-12 17:03:32

标签: python numpy scipy

具有函数f(x,y,z),我需要解决限制f(x,y,z)= 0然后绘制它。我试图为每对(y,z)找到f(x,y,z)= 0的值x:

from numpy import *
from scipy.optimize import fsolve

def func(x,y,z):
    return x+y+z

y = linspace(0,1,100)
z = linspace(0,1,100)
x0 = zeros((y.size,z.size)) + 0.5 # the initial guess
yz = (y[:,newaxis],z[newaxis,:]) # the other parameters
x, info, iterations, message = fsolve(func,x0,yz)
contour(y,z,x)

Python(2.7.5)说“TypeError:fsolve:'func'参数'func'的输入和输出形状之间存在不匹配。”

但如果我自己测试它,它会给出相同的形状:

func(x0,y[:,newaxis],z[:,newaxis]).shape == x0.shape

返回True。

为什么fsolve()抱怨?

2 个答案:

答案 0 :(得分:2)

fsolve期望x参数和func的返回值是标量或一维数组。您必须修改代码才能使用展平的x值。 E.g。

def func(x, y, z):
    x = x.reshape(y.size, z.size)
    return (x + y + z).ravel()
对于fsolve的调用

以及类似的内容:

sol, info, ier, mesg = fsolve(func, x0.ravel(), args=yz, full_output=True)
x = sol.reshape(y.size, z.size)

答案 1 :(得分:2)

以下是与scipy.optimize tutorial中广告的krylov方法的比较:

from numpy import linspace, zeros, newaxis
import time
from scipy.optimize import root

def func(x,y,z):
    x = x.reshape(y.size, z.size)
    f = x + y + z
    f = f.ravel()
    return f

n = 50
y = linspace(0,1,n)
z = linspace(0,1,n)
x0 = zeros((y.size,z.size)) + 0.5 # the initial guess
yz = (y[:,newaxis],z[newaxis,:]) # the other parameters

start = time.time()
sol1 = root(func, x0.ravel(), args=yz, method='hybr', tol=1e-7)  # same as fsolve
x1 = sol1.x.reshape(y.size, z.size)
print("(fsolve) time taken (sec): %g" % (time.time() - start,))
print("(fsolve) successful: %r (%s)" % (sol1.success, sol1.message))
print("(fsolve) max error: %g" % (abs(func(x1, *yz)).max(),))

start = time.time()
sol2 = root(func, x0.ravel(), args=yz, method='krylov', tol=1e-9)
x2 = sol2.x.reshape(y.size, z.size)
print("(krylov) time taken (sec): %g" % (time.time() - start,))
print("(krylov) successful: %r (%s)" % (sol2.success, sol2.message))
print("(krylov) max error: %g" % (abs(func(x2, *yz)).max(),))

打印

(fsolve) time taken (sec): 26.9296
(fsolve) successful: False (The iteration is not making good progress, as measured by the 
  improvement from the last ten iterations.)
(fsolve) max error: 1.52656e-16
(krylov) time taken (sec): 0.0173709
(krylov) successful: True (A solution was found at the specified tolerance.)
(krylov) max error: 1.11022e-16