![](/img/trans.png)
[英]How do I find the pseudo-inverse from Apache Commons Math - Java library
[英]How to find the inverse of a matrix using Apache Commons Math library in Java?
我正在嘗試使用 Apache Commons Math Library 找到矩陣的逆。
以下是我這樣做的嘗試:
BigReal[][] leftMatrixData = new BigReal[][] {
{ new BigReal(1), new BigReal(0), new BigReal(0), new BigReal(0) },
{ new BigReal(1), new BigReal(0), new BigReal(1), new BigReal(0) },
{ new BigReal(1), new BigReal(1), new BigReal(0), new BigReal(0) },
{ new BigReal(1), new BigReal(1), new BigReal(1), new BigReal(1) },
};
FieldMatrix<BigReal> leftMatrix = MatrixUtils.createFieldMatrix(leftMatrixData);
FieldMatrix<BigReal> leftMatrixInverse = new FieldLUDecomposition<>(leftMatrix)
.getSolver()
.getInverse();
當我運行它時,我收到以下錯誤:
org.apache.commons.math3.exception.MathArithmeticException: zero not allowed here
at org.apache.commons.math3.util.BigReal.divide(BigReal.java:255)
at org.apache.commons.math3.util.BigReal.divide(BigReal.java:39)
at org.apache.commons.math3.linear.FieldLUDecomposition.<init>(FieldLUDecomposition.java:160)
當我根據上述錯誤消息轉到FieldLUDecomposition.java
第 160 FieldLUDecomposition.java
,我看到庫認為這個矩陣是奇異矩陣,即它認為它沒有逆矩陣:
public T getDeterminant() {
if (this.singular) { <---- this is line 160
return (FieldElement)this.field.getZero();
} else {
int m = this.pivot.length;
T determinant = this.even ? (FieldElement)this.field.getOne() : (FieldElement)((FieldElement)this.field.getZero()).subtract(this.field.getOne());
但是,對 WolframAlpha 進行快速檢查表明該矩陣具有非零行列式並且確實具有逆:
所以問題是 - 我做錯了什么,我如何找到矩陣的逆? 我是否使用了錯誤的求解器?
下面是基於apache common math 3.6.1
一票是關於這個問題的提出,我提交了一個補丁來解決這個問題和修復版本將是4.0(尚未發布截至2021年7月19日)
問題的原因是BigReal
equals
方法
@Override
public boolean equals(Object other) {
if (this == other){
return true;
}
if (other instanceof BigReal){
return d.equals(((BigReal) other).d);
}
return false;
}
其中 d 是BigDecimal
, BigReal
的支持值。 這會導致當兩個BigReal
具有相同值但不同比例的d
時等於比較返回不想要的結果,並在初始化FieldLUDecomposition
時導致錯誤。 對於BigDecimal
我們應該檢查
return d.compareTo((BigReal) other) == 0;
反而。
BigReal
復制為本地類並更改equals
)是否有幫助。RealMatrix
, MatrixUtils
提供方便的inverse
方法import org.apache.commons.math3.linear.MatrixUtils;
import org.apache.commons.math3.linear.RealMatrix;
public class CalculateInverse {
public static void main(String[] args) {
double[][] matrixData = new double[][]{
{1, 0, 0, 0},
{1, 0, 1, 0},
{1, 1, 0, 0},
{1, 1, 1, 1}
};
RealMatrix matrix = MatrixUtils.createRealMatrix(matrixData);
RealMatrix inverse = MatrixUtils.inverse(matrix);
System.out.println(inverse);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.