Ostrich
Ostrich

Reputation: 39

root finding for a loop (newton) several values

I am trying to find the root of an equation for several values of other exogenous variables. For example, the code below generate 10 values of z and tau

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import newton

#Declare variables
alpha    = 0.33    
r        = 1.04    
sample_N = 10      
###########
corr  = 0.9   # corr: controls the correlation between 
mean  = [0,0] # mean of z and tau
cov   = [[1,corr], [corr,1]]   #covariance

z,tau = np.random.multivariate_normal(mean, cov, sample_N).T
z     = np.exp(z)   # z: converted into z=e^z so that the domain of
                    # z is [0,inf) rather than (-inf,inf)
rho   = 0.5         # tau: converted into (1+e^(rho*-tau))^(-1/rho) 
                    # so that the domain is [0,1] rather than (-inf,inf)
tau   = (1+np.exp(-rho*tau))**(-1/rho)

I would like to find the root of the equation defined in the function below for each pair (z,tau). I can find for specific values, e.g., z[0], tau[0], but I am having a hard time finding a way to do it for all 10 values.

def fun(x):
    Z = z[0]
    y = tau[0]
    Y = - np.log((1 - 0.5**x)) + np.log(x*Z) + np.log(0.5**x) + y
    return Y
newton(fun, 2)

Is it possible? how to do it? Thanks in advance

Upvotes: 1

Views: 264

Answers (1)

joni
joni

Reputation: 7157

The newton method only works for functions of a single variable. In order to find the root of a function of multiple variables, you can use scipy.optimize.root instead:

from scipy.optimize import root

def fun(x, Z, y):
    Y = - np.log((1 - 0.5**x)) + np.log(x*Z) + np.log(0.5**x) + y 
    return Y.flatten()

# z and tau are the same as in your code snippet
res = root(lambda x: fun(x, z, tau), x0=np.ones(z.size))

Then res.x contains the solution

array([1.70258842, 4.07240209, 3.03439042, 2.42066177, 5.40377196,
       3.41517153, 3.65460192, 0.47339928, 0.4137104 , 3.6828219 ])

Upvotes: 1

Related Questions