0
private void fillInState() {
    state [0][0] = 0.6;
    state [0][1] = 0.4;
    state [1][0] = 0.3;
    state [1][1] = 0.6;
    state [1][2] = 0.1;
    state [2][0] = 0.7;
    state [2][2] = 0.3;
}


private void fillInNext() {
    next [0][0] = 1.0;
}

public void chain (int time) { 
    for(int i=0; i<time;i++) {
        for( int j=0; j<3;j++) { 
            double temp = 0;
            for(int k=0;k<3;k++) {
                temp = state[k][j] * next [k][i] + temp;

                if(k==2) {
                    next[j][i+1]=temp;                   
                }
            }
        }
    }
}

The expected answer should be:

1.0 0.6 0.48  
0.0 0.4 0.48  
0.0 0.0 0.04

But the answer in blueJ is:

1.0 0.6 0.48  
0.0 0.4 0.48  
0.0 0.0 0.04000000000000001  

Anyone knows what happened? Is that about the Double class or blueJ?

demongolem
  • 9,474
  • 36
  • 90
  • 105

2 Answers2

1

This is simply due to floating-point errors. You can always format the output using something like printf:

double d = 0.04000000000000001;
System.out.println(d);
System.out.printf("%.2f%n", d);
0.04000000000000001
0.04

See Oracle's tutorial Formatting Numeric Print Output.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • What if I want to save the result back to the array? – user3302184 Feb 12 '14 at 15:11
  • @user3302184 Then you can just save it normally. The formatting is only for converting the actual double to a visual representation; it has no bearing on the double's value itself. – arshajii Feb 12 '14 at 15:13
0

This is because of how floating point arithmetic works. Try looking at this for some detail. Basically it is not possible to represent arbitrary Decimal numbers in a finite number of binary digits using the normal floating point representation.

If you need your arithmetic to match closely with Decimals then use BigDecimal.

Often you can just ignore these errors by rounding the result you output to screen etc.

brain
  • 5,496
  • 1
  • 26
  • 29