Is there a way to solve a non-linear equation in nested arrays?

89 Views Asked by At

I want to solve for m the following equation numerically on Python:

C_left = np.cosh(m*(T/2 - t))/np.cosh( m*(T/2 - T - 1) ).

In this case, C_left is a nested array of floats with dimensions 15 x 47 and T = 48. My intend outcome is a nested array sol with the same dimensions as C_left, in which the entries are the solutions to the above equation. For example, sol[0] has to contain the solutions for C_left[0] element/array (sol[0][2] is the solution for the element C_left[0][2]).

I have been trying to use the several equation solving functionalities that scipy offer, for example scipy.optimize.fsolve and scipy.optimize.bisect.

My most promising attempt was solving for only one element at a time, for example:

import scipy.optimize 
T = 48

C_left = [[C_all[j][t]/C_all[j][t+1] for t in range(47)] for j in range(15)]

def func1(m):
    return C_left[0][2] - np.cosh(m*(T/2 - 2))/np.cosh( m*(T/2 - T - 1) ) 

test = scipy.optimize.fsolve(func1,0.5)

and still I encountered the error:

RuntimeWarning: The iteration is not making good progress, as measured by the 
  improvement from the last five Jacobian evaluations.
  warnings.warn(msg, RuntimeWarning)

even though it actually outputted a solution!

My main problem is that I can't seem to figure out a way to solve this without unfolding the gigantic multidimensional array.

If anyone needs, I can provide the text for the 15 x 47 array.

EDIT: A new attempt !

Using the following answer Creating functions in a loop , I was able to create a for loop that creates a function for each element of C_left. Then, I used those functions to solve the equation using scipy.optimize.fsolve.

import scipy.optimize 

T = 48
C_left = [[C_all[j][t]/C_all[j][t+1] for t in range(47)] for j in range(15)]
den = T/2 - T - 1

sol = [[0]*47]*15

def func_fac(m):
    def f():
        z = C_left[k][j] - np.cosh(m*(T/2 - j))/np.cosh(m*den)
        return z
    return f

for k in range(15):
    for j in range(47):
        sol[k][j] = scipy.optimize.fsolve(func_fac,0.5)

But I encountered another error

error: Result from function call is not a proper array of floats.
0

There are 0 best solutions below