【发布时间】:2018-06-19 04:09:27
【问题描述】:
我找到了算法的正确结果 我可以将这段代码实现到 Java 中吗?
import numpy as np
from scipy.linalg import eig
transition_mat = np.matrix([
[0.8, 0.15, 0.05],\
[0.075, 0.85, 0.075],\
[0.05, 0.15,0.8 ]])
S, U = eig(transition_mat.T)
stationary = np.array(U[:, np.where(np.abs(S - 1.) < 1e-8)[0][0]].flat)
print stationary
print np.sum(stationary)
stationary = stationary / np.sum(stationary)
print stationary
我在 Java 中实现了这段代码,但结果是错误的
Matrix A = new Matrix(transition);
A = A.transpose();
Matrix x = new Matrix(N, 1, 1.0 / N); // initial guess for eigenvector
for (int i = 0; i < 50; i++) {
x = A.times(x);
x = x.times(1.0 / x.norm1()); // rescale
}
// compute by finding eigenvector corresponding to eigenvalue = 1
EigenvalueDecomposition eig = new EigenvalueDecomposition(A);
Matrix V = eig.getV();
double[] real = eig.getRealEigenvalues();
for (int i = 0; i < N; i++) {
if (Math.abs(real[i] - 1.0) < 1E-8) {
x = V.getMatrix(0, N-1, i, i);
x = x.times(1.0 / x.norm1());
System.out.println("Stationary distribution using eigenvector:");
x.print(9, 6);
}
}
【问题讨论】:
-
您当前/预期的结果是什么? (编辑您的问题以添加它)
-
结果为空
-
如果我删除 if (Math.abs(real[i] - 1.0)
-
在 Java 中 -0.040173, -0.147368, 0.812459 在 Python 中 -0.40824829 -0.81649658 -0.40824829
标签: java eigenvalue markov-chains