python中矩阵的乘法导致类型错误

时间:2017-01-01 13:42:09

标签: python python-2.7 numpy

在尝试从以下函数x(n+1) = 1 -a*x(n)**2 + y(n); y(n+1) = b*x(n)的jacobian矩阵计算点积时,我收到以下错误:vec1 = J*vec1 TypeError: can't multiply sequence by non-int of type 'list'

import numpy as np
a, b = 1.2, 0.4
x, y = 0., 0.

vec1 = [[1], [0]]
vec2 = [[0], [1]]

for i in range(500):
    x1 = 1. - a*x**2 + y
    y1 = b*x
    x = x1
    y = y1
    J = [[-2.*a*x, 1], [b, 0]]
    vec1 = J*vec1
    vec2 = J*vec2
    dotprod1 = np.dot(vec1,vec1)
    dotprod2 = np.dot(vec1,vec2)
print(dotprod1)
print(dotprod2)

1 个答案:

答案 0 :(得分:7)

vec1vec2应该是numpy数组而不是Python列表:

import numpy as np
from numpy import dot, exp, log, sqrt
a, b = 1.2, 0.4
x, y = 0., 0.

vec1 = np.array([[1], [0]])
vec2 = np.array([[0], [1]])

for i in range(500):
    x1 = 1. - a*x**2 + y
    y1 = b*x
    x = x1
    y = y1
    J = [[-2.*a*x, 1], [b, 0]]
    vec1 = J*vec1
    vec2 = J*vec2
    dotprod1 = dot(vec1,vec1)
    dotprod2 = dot(vec1,vec2)
print(dotprod1)
print(dotprod2)

输出:

[[  2.32511745e+112   1.52483358e+056]
 [  0.00000000e+000   0.00000000e+000]]
[[  1.07150861e-199   0.00000000e+000]
 [  0.00000000e+000   0.00000000e+000]]