Scipy fsolve不能将稀疏矩阵作为雅可比

时间:2017-09-10 21:10:18

标签: python optimization scipy sparse-matrix

我有以下代码,它工作正常(当然它不会收敛):

import numpy as np
from scipy.optimize import fsolve
from scipy.sparse import csr_matrix

T = 100

def recurrence(p):
    return p[2] - p[1] + 100 

def equations(p):
    n = len(p)
    return [p[0], p[n-1]-1] + [recurrence(p[i-1:i+2])
                               for i in range(1, n-1)]

def jacobian(p):
    J = np.ones((T+1, T+1))
    return J

p = np.ones(T + 1)
sol = fsolve(equations, p, fprime=jacobian)

然而,当我更改jacobian以返回稀疏矩阵时,它不再起作用了:

def jacobian(p):
    J = np.ones((T+1, T+1))
    return csr_matrix(J)

TypeError: fsolve: there is a mismatch between the input and output shape of the 'fprime' argument 'jacobian'.Shape should be (101, 101) but it is (1,).

这里有解决方法吗?当然这只是一个例子,但我正在使用另一个具有更大T值的系统。

0 个答案:

没有答案