0

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

3
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by debee
Featured Replies
  • 1
    Ezzaral 2,714   8 Years Ago

    Multiplying at those magnitudes are putting you beyond the precision of double. Use [URL="http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html"]BigDecimal [/URL] instead. [code=java]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[/code] Read More

1

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

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

0
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 article has been dead for over six months. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.