Search code examples
javabigdecimal

BigDecimal adding problems


There's this code. The problem is the following: numar computes as it should, but fails to add to pi, which remains 0.0, unchanged. why?

 public static void piLeibniz(int numarZecimale)
{
    String piReal = "3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679";
    long t1 = System.currentTimeMillis();

    BigDecimal numar ;
    BigDecimal pi = new BigDecimal("0.0");

    for(int i = 0; i<=100000000;i++)
    {
        numar = new BigDecimal( 4*((Math.pow(-1, i))/((2*i)+1)));
        pi = pi.add(numar);
       //System.out.println(numar);
        String piString = pi.toString();
        System.out.println(piString);

        if(!piString.substring(0, numarZecimale).equals(piReal.substring(0, numarZecimale)))
        {
        } else {
            long t2 = System.currentTimeMillis();
            System.out.println("Pi este:" + piReal.substring(0, numarZecimale)+ " calculat in " + (t2-t1) + " ms");
            break;
        }

    }
}

EDIT (edited as Reimeus said): If the method's parameter is higher than 3, it throws StringIndexOutOfBoundsException. why?


Solution

  • add returns a new BigDecimal value which is immutable. The original value needs to be assigned to the result of the method otherwise the value of pi will remain at its original value

    pi = pi.add(numar);