user3251256
user3251256

Reputation: 165

BigDecimal multiplication returns 0?

I'm a bit of a newbie at Java and I have to multiply 52 numbers with each other ranging anywhere from 0 to 2000. I already tried using *= without BigDecimal but the result gives me 0.0.

Here is my code:

BigDecimal productOfStock1 = BigDecimal.ZERO;

for(int k = 1; k <= N; k++){

    for(int i = 1; i <= n; i++){
      if (i == 1){
        stockPrice[k][i] = stockZero*Math.pow(e, form + sigma*(randomno.nextGaussian()));
      }
      else {
        stockPrice[k][i] = stockPrice[k][i-1]*Math.pow(e, form + sigma*(randomno.nextGaussian()));

      }
      //sumOfStock += stockPrice[k][i];
      //productOfStock *= stockPrice[k][i];
      productOfStock1 = productOfStock1.multiply(BigDecimal.valueOf(stockPrice[k][i]));

      System.out.println(/*"Stock at [" + i + "] for N = " + N + "  and path number " + k + " is " + */stockPrice[k][i]);


  }
  }

System.out.println(productOfStock1);

This gives me 0E-637 instead of the big number it is supposed to give me. Any help is appreciated.

Upvotes: 0

Views: 667

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240870

BigDecimal productOfStock1 = BigDecimal.ZERO;

you need to initialize it with 1, because

0 * X = 0

(except for X= 1/0 :) )

Upvotes: 5

poy
poy

Reputation: 10507

Don't initialize productOfStock1 to 0, use 1 instead. Otherwise, you'll always be multiplying by 0.

Upvotes: 1

Related Questions