I am a bit of a newbie at Java and I have a program that generates 52 different stock prices that can range anywhere from 0 to approximately 2000. My program also generates N number of different stock price "paths". I want to find out what the product of these 52 stock prices is. I have decided to use BigDecimal.

BigDecimal[] productOfStock1 = new BigDecimal[N+1];
    for(int k = 1; k <= N; k++){
      productOfStock1[k] = BigDecimal.ONE;
    }

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()));

      }

      productOfStock1[k] = productOfStock1[k].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("Product : " + productOfStock1[k]);

The problem that I ran into was that when I copy the values of stockPrice[1][i] for i = 1, ..., 52 into excel and calculate the product, I get a different value from the BigDecimal value from my code. Any help is appreciated.

有帮助吗?

解决方案

BigDecimal is correct. Excel is incorrect.

BigDecimal is designed to provide exact precision. So much so, that operations that would result in repeating decimals throw an exception, because an exact representation is not possible:

BigDecimal.ONE.divide(new BigDecimal(3));

Causes an ArithmeticException with the message:

Non-terminating decimal expansion; no exact representable decimal result

Excel uses floating point arithmetic, which is imprecise, or rather has a maximum level of precision. With it, small fractional errors may accumulate potentially leading to a mathematically "incorrect" answer.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top