Hello there,

I am trying to build a square matrix of the type Double, with the following code:

for( i = 0; i < weightVector.length; i++) 

      for( j =0; j< weightVector.length; j++) 

         {
             weightMatrix[i][j]= weightVector[i]* weightVector[j];
             if(i==j)                                                               weightMatrix[i][i] += 0.0001;  
        }

The problem is each time the vector "weightVector" has a very small value (e.g the multiplication of the values 1.190597027811988E-273 and -2.513498651481222E-273) it gives zero as an answer, but if i work this out with a calculator, it gives me the right answer. Can you tell me why my programme is approximating its answer to zero, please?

Recommended Answers

All 6 Replies

Multiplying at those magnitudes are putting you beyond the precision of double. Use BigDecimal instead.

double a = 1.190597027811988E-273;
double b = -2.513498651481222E-273;
System.out.println("double: "+(a*b));
// double: -0.0

BigDecimal c = new BigDecimal(a);
BigDecimal d = new BigDecimal(b);
System.out.println("BigDecimal: "+new DecimalFormat("0.#######E0").format(c.multiply(d)));
// BigDecimal: -2.992564E-546
commented: A great poster, always helpful +2

Was trying to figure that out for debee too Ezzaral! You are great!

Thanks for your help. I do really appreciate

Please, i was trying to figure out how you can declare an array with the BigDecimal class. Can you help with this please

BigDecimal[][] weightMatrix = new BigDecimal[4][4];
for (int i=0; i<weightMatrix.length; i++){
    for (int j=0; j<weightMatrix[i].length; j++){
        weightMatrix[i][j] = new BigDecimal(yourValue);
    }
}

Thank you very much, that's very kind of you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.