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:
Having the function f(x,y,z), I need to solve the restriction f(x,y,z) = 0 and then plot it. I tried to find for each pair (y,z) the value x for which f(x,y,z) = 0:
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'的输入和输出形状不匹配."
Python (2.7.5) says "TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'func'."
但是,如果我自己进行测试,它会具有相同的形状:
But if I test it myself, it gives the same shape:
func(x0,y[:,newaxis],z[:,newaxis]).shape == x0.shape
返回True.
为什么fsolve()抱怨?
Why does fsolve() complain?
推荐答案
fsolve
期望x
参数和func
的返回值是标量或一维数组.您必须修改代码才能使用平坦的x
值.例如
fsolve
expects the x
argument and the return value of func
to be a scalar or one-dimensional array. You'll have to modify your code to work with flattened x
values. E.g.
def func(x, y, z):
x = x.reshape(y.size, z.size)
return (x + y + z).ravel()
和类似这样的内容调用fsolve
:
and something like this for the call to fsolve
:
sol, info, ier, mesg = fsolve(func, x0.ravel(), args=yz, full_output=True)
x = sol.reshape(y.size, z.size)
这篇关于Python fsolve()抱怨形状.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!