0

I need some help to write my code more efficiently. The below code aims to solve a non-linear equation for a variable hi given the elements in some arrays. For example:

import numpy  as np 
import tensorflow as tf
import scipy.optimize 

kon = 0.01
mu  = 1.5
fi  = 0.5 
kappa = 22

n =100
xs = tf.random.normal(shape=(n,), stddev=0.2)
eps = tf.random.normal(shape=(n,), stddev=0.17)
z = tf.sigmoid(tf.random.normal(shape=(n,), stddev=0.22))

# non-linear equation to solve for leisure 
def F(hi):
  return (mu/fi)*np.log(hi) -(1-mu)*kappa*(hi)**(1+(1/fi))-mu*(np.log(w*ei*xs)-np.log(kon))-np.log(ze)
hvec = np.empty((0,))
# leisure today 
for ze,ei,xs in zip(z, eps, x0):
    ei=tf.exp(ei)
    xs=tf.exp(xs)
    htemp = scipy.optimize.newton_krylov(F, 0.5)
    hvec = np.append(hvec, htemp)   

Here, z,eps,x0 are arrays of size n (e.g. n=100)

Is there a more efficient way to do the same thing? for example, by avoiding the loop ?

I basically want to solve for hi for each element in these three arrays.

Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60
msh855
  • 1,493
  • 1
  • 15
  • 36
  • efficient in terms of what? – Zabir Al Nazi Apr 19 '20 at 06:18
  • e.g avoiding the loop? – msh855 Apr 19 '20 at 06:19
  • add a minimal reproducible example with z, ei, xs so that it can be run. – Zabir Al Nazi Apr 19 '20 at 06:20
  • @msh855 you mean to say, you don't want to write a loop?, reason I am asking, `scipy.optimize.newton_krylov` this itself has a loop inside it – Dickens A S Apr 19 '20 at 06:24
  • you can use `fsolve` -- https://stackoverflow.com/questions/8739227/how-to-solve-a-pair-of-nonlinear-equations-using-python – Dickens A S Apr 19 '20 at 06:26
  • @ZabirAlNazi added. Thanks – msh855 Apr 19 '20 at 06:27
  • @DickensAS. That's not a pair of equations that I am trying to solve. It's a single non-linear equation, which I have to solve many times because its parameters change. Please read again my example and question more carefully. – msh855 Apr 19 '20 at 07:11
  • you still call `fsolve` with `args` passing to your `F` with wild card data like `*data`, and you can pack and unpack tuples or vectors using formulas inside `F` -- try this search result https://stackoverflow.com/search?q=%5Bscipy%5D+fsolve – Dickens A S Apr 19 '20 at 07:45
  • @DickensAS Thanks for the suggestion. Since I have a minimum working example, why you don't try it and post it as an answer if it works and replicates the same thing I did? I am not very experienced python use, hence I asked for help here. – msh855 Apr 19 '20 at 08:06

0 Answers0