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?

Edited by Dani: Formatting fixed

10 Years
Discussion Span
Last Post by debee

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
Votes + Comments
A great poster, always helpful

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);
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.