[英]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.