0

I know how to use fsolve in scipy

from scipy.optimize import fsolve
import numpy as np
k=4
def equations(p):
    x,y=p
    eq_1 = x+y-k
    eq_2 = x-y
    return (eq_1,eq_2)
fsolve(equations, (0,0))

But I don't know how to vectorize this function if k is a numpy array. (I could do it in a loop for different value of k, but if will take a lot of time). Is there a solution like :

from scipy.optimize import fsolve
import numpy as np
k=np.arange(10000)
def equations(p):
    x,y=p
    eq_1 = x+y-k
    eq_2 = x-y
    return (eq_1,eq_2)
fsolve(equations, (np.zeros(10000),np.zeros(10000)))

Thank's a lot if you have any idea

EDIT : The link that some of you give below increases the calculation time as each line are not necessary independant. For example, you can test those two code :

s=1000

#With array
t0=time.time()
k=np.arange(s)
def equations(p):
    eq_1 = p**2-k
    return (eq_1)
res=fsolve(equations, np.ones((s)))
print(time.time()-t0)

#With loop
t0=time.time()
res=np.zeros((s))
i=0
def equations(p):
    eq_1 = p**2-i
    return (eq_1)
while i<s:
    res[i]=fsolve(equations, 1)[0]
    i+=1
print(time.time()-t0)

Result

10.85175347328186
0.05588793754577637

Is there a way to avoid a loop but to keep a good speed with vectorize function

gonzague
  • 3
  • 3
  • Does this answer your question? [Is there a way I can vectorize fsolve?](https://stackoverflow.com/questions/10828477/is-there-a-way-i-can-vectorize-fsolve) – AMC Dec 17 '19 at 10:47
  • This looks like a duplicate. Had you checked? – AMC Dec 17 '19 at 10:47
  • Thank's, I already check that link. But in that case fsolve is probably going to be very slow, as it will think each line are not necessary independant. Is there a way to tell fsolve that he can separetly evaluate x[i] and y[i] for each value of k[i], and that (x[i],y[i]) is not linked with (x[j],y[j]). – gonzague Dec 17 '19 at 11:06

1 Answers1

1

Not directly.

There is cython_optimize interface though, https://docs.scipy.org/doc/scipy/reference/optimize.cython_optimize.html

So you can drop to cython and implement the loops manually. YMMV though

ev-br
  • 24,968
  • 9
  • 65
  • 78