繁体   English   中英

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

[英]Python fsolve() complains about shape. Why?

具有函数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()抱怨?

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

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)

这是与scipy.optimize教程中广告的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM