0

I have a system of this type:

a = alpha(x,k)  
b = beta(x,k,alpha)  
gamma(x,k,a,b) = 0

with x, a, and b as unknowns. Is it correct to set it up/solve like the example below?

k=1.5
def gamma(x,k):
    def alpha(x,k):
        return (x-k)**3
    def beta(x, f1):
        return x + f1(x,k)
    return x**2 - alpha(x,k) - beta(x, alpha)*x
x, info, flag, msg = fsolve(gamma, 0., args=(k), full_output=True)
print x
print info
xp = np.linspace(-5, 5)
yp = [gamma(xx, k) for xx in xp]
plt.plot(xp, yp, '.-b')
plt.grid()

which prints out:

[1.49999677]
{'qtf': array([-8.8817842e-16]), 'nfev': 44, 'r': array([2.57880614e-10]), 'fjac': array([[-1.]]), 'fvec': array([0.])}

If so, how can I get fsolve to return both roots, as shown in the graph? graph of solutions from gamma

Thanks in advance!

asdf1234
  • 13
  • 4
  • you could start multiple instances of fsolve with different initial values and collect the outputs – Moritz Aug 08 '18 at 10:03
  • note: it is possible to directly write `yp = gamma(xp, k)`, for the plot, since `gamma` works with Numpy nd-arrays – xdze2 Aug 08 '18 at 10:20

1 Answers1

0

If you set the starting point at -2 instead of zero, it finds the left root. If you use [-2., 0] instead fsolve return both roots (see this answer):

x, info, flag, msg = fsolve(gamma, [-2., 0], args=(k), full_output=True)
print(x)
# [-1.          1.49999586]

The difficult question is how to choose the starting points...

xdze2
  • 3,986
  • 2
  • 12
  • 29
  • thanks! exactly "how to choose starting points..." and related looping/cleaning the solution(s) is a pain. I suppose the problem is set up correctly then? it's just the functionality of gathering multiple (or all) roots that is a little bumpy? – asdf1234 Aug 08 '18 at 10:11
  • I think the problem is set up correctly. I will move the `beta` and `alpha` functions out of `gamma` but it is not a huge change. By the way, I think this is not the actual problem you want to solve, because this is a polynomial equation and the roots are `-1` and `k`. The method to choose the starting point will change with the kind of problem: Is it reasonable to plot the graph and check? Are the roots expected in a certain range? Is the number of roots known? ...etc – xdze2 Aug 08 '18 at 12:59
  • Thanks again. Indeed, this gamma here is just an example and my problem uses different functions. It is doable to plot and check (and it's what I currently do), but not preferable. In the real case, I am looking for the roots of a function derived from a least-squares minimisation, its output is not known a priori, as well as the number/range of its roots. – asdf1234 Aug 09 '18 at 00:27