Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

numpy - Python fsolve() complains about shape. Why?

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) 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

returns True.

Why does fsolve() complain?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...