user2948708
user2948708

Reputation: 115

Why is this division with BigDecimal returning 0?

I am using the Chudnovsky algorithm to compute PI:

Here is the code:

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Scanner;

public class main {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int summationUpperLimit;
        int precision;

        System.out.println("Enter the summation upper limit: ");
        summationUpperLimit = reader.nextInt();

        System.out.println("Enter the precision: ");
        precision = reader.nextInt();

        System.out.println(calculatePI(summationUpperLimit, precision));
    }

    private static int calculateFactorial(int n) {
        int factorial = 1;

        for (; n > 1; n--) {
            factorial = factorial * n;
        }

        return factorial;
    }

    private static BigDecimal calculatePI(int summationUpperLimit, int precision) {
        BigDecimal reciprocalOfPI = BigDecimal.ZERO;
        reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

        for (int k = 0; k <= summationUpperLimit; k++) {
            BigDecimal numerator = BigDecimal.valueOf(12 * Math.pow(-1, k) * calculateFactorial(6 * k) * (13591409 + 545140134 * k));
            numerator.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);
            BigDecimal denominator = BigDecimal.valueOf(calculateFactorial(3 * k) + Math.pow(calculateFactorial(k), 3) * Math.pow(640320, 3 * k + 1.5));
            denominator.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);
            // The issue is the line below:
            reciprocalOfPI = reciprocalOfPI.add(numerator.divide(denominator, BigDecimal.ROUND_HALF_UP));
        }

        return reciprocalOfPI.pow(-1, MathContext.DECIMAL128);
    }
}

I set the following input:

summationUpperLimit = 0
precision = 100

In debugging mode, I checked the output:

numerator = 163096908
denominator = 512384048.99600077
reciprocalOfPI = 0 (this value was taken after the division)

163096908 / 512384048.99600077 doesn't equal 0 so why is the expression reciprocalOfPI = reciprocalOfPI.add(numerator.divide(denominator, BigDecimal.ROUND_HALF_UP)); setting reciprocalOfPI to 0?

My justification for setting scale = precision - 1:

  1. Precision is the total number of digits. Scale is the number of digits after the decimal place.

  2. In PI, there is only 1 digit before the decimal.

  3. precision = scale + 1 and therefore scale = precision - 1

Upvotes: 2

Views: 1145

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

It's probably caused by

reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

which should be

reciprocalOfPI = reciprocalOfPI.setScale(precision - 1, BigDecimal.ROUND_HALF_UP);

BigDecimal is immutable. All its "mutating" methods return a new BigDecimal, leaving the original one unchanged.

Upvotes: 4

Related Questions