Reputation: 3
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
Upvotes: 0
Views: 490
Reputation: 26110
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
Upvotes: 1