繁体   English   中英

Java矩阵和数字

[英]Java matrices and numerics

所以我刚开始用Java做数值方法;

// I have a matrix class that has get, set methods for creating matrices; have used those in the method below.
// The method below computes a Matrix and prints as well returns it.

public Matrix computeA(){

    int nrows = A.getNumRows();
    int ncols = A.getNumCols();

    for(int i = 0; i < nrows; i++){
        double sum = 0.0;
        for (int j = 0; i< ncols; j++){
                         if (i!=j){
             A.setElement(i,j, aijCalc(i,j) );} // aijCalc is numeric method; setElement has parameters (i, j, value)
        }
    A.print();
    return A;
}

现在,这是我不明白该怎么做:对角线,其中i = j,矩阵条目是1 - (该行中所有aij条目的总和(对于i!= j))。 如何在上述方法中对此进行编码?

我当前的输出(没有任何四舍五入看起来像这样):

0.0 0.026055555555555554 0.0248125 0.050694444444444445 0.05872222222222222 0.030208333333333334

-0.0053750000000000004 0.0 0.00792361111111111 0.01813194444444444 0.02361111111111111 0.009874999999999998

-0.0013854166666666667 -0.005291666666666666 0.0 0.008680555555555556 0.009041666666666667 0.0

0.0 0.009041666666666667 0.008680555555555556 0.0 -0.005291666666666666 -0.0013854166666666667

0.009874999999999998 0.02361111111111111 0.01813194444444444 0.00792361111111111 0.0 -0.0053750000000000004

0.030208333333333334 0.05872222222222222 0.050694444444444445 0.0248125 0.026055555555555554 0.0

(它有0,其中i = j)

它应该看起来像这样:

0.810 0.026 0.025 0.051 0.059 0.030

--0.005 0.946 0.008 0.018 0.024 0.010

--0.001 --0.005 0.989 0.009 0.009 0.000

0.000 0.009 0.009 0.989 --0.005 --0.001

0.010 0.024 0.018 0.008 0.946 --0.005

0.030 0.059 0.051 0.025 0.026 0.810

谢谢!

那些额外的零实际上是“谎言”。

建议:只需将数字格式化为实际精度(例如四位或五位小数)。

例:

System.out.println (String.format ("%11.2f", x);

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

PS:

浮点“printf”与其他所有语言完全相同 :包括C#和C ++。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM