Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with bitwise operations to optimize Java Math

Tags:

java

In my Java class, I have to calculate the value of Pi accurate to 15 decimal places using the Bailey–Borwein–Plouffe formula. In the formula, I need to calculate the 16 to the power of n (integer from 1 to 50 000 000);

There is the formula I am working with

The Bailey–Borwein–Plouffe formula

And here is my code to calculate that:

double value = 0.0;

//Calculates and increments value by using the BBP formula
for(int i = 0; i < iterations; i++) {
    if(i == 0) {
        value += (1 / 1) * (
                 (4.0 / ((8 * i) + 1)) - 
                 (2.0 / ((8 * i) + 4)) - 
                 (1.0 / ((8 * i) + 5)) - 
                 (1.0 / ((8 * i) + 6)) );
    } else {
        value += (1.0 / (2L<<(i<<2L))) * (
                 (4.0 / ((8 * i) + 1)) - 
                 (2.0 / ((8 * i) + 4)) - 
                 (1.0 / ((8 * i) + 5)) - 
                 (1.0 / ((8 * i) + 6)) );
    }
}

The problem is, I am using a bitwise operation (shift left <<) to optimize the code, as we are given bonus marks if we make the program as fast as possible. And for some reason, no matter what I try, the resulting number calculated from Pi is simply too large to work with. I am able to get the numbers 1 to 1.5324955e+54. After that, the numbers overflow and I get 1 or 0. I am trying to get 3.14159 etc but I get 3.1382357295632852 because of this data overflow.

Can anyone help me with this? Or is it simply not worth using bitwise operations to calculate power?

like image 840
Electric Fountain Co Avatar asked Oct 16 '25 18:10

Electric Fountain Co


2 Answers

The smallest value that is expressable as a greater-than-zero double is 2-2048. That formula is going to hit zero as a double for every term above (2048/4), which is 512. Going up to 50,000,000 is 49,999,488 too far.

like image 182
Andrew McGuinness Avatar answered Oct 18 '25 09:10

Andrew McGuinness


You only need 15 digits? Here you go:

class Class {
  private static final int ITERATION_COUNT = 15;


  public static void main(final String... args) {
    System.out.println(generatePi());
  }

  private static double generatePi() {
    double pi = 0;
    long sixteenPowK = 1;
    for (int k = 0; k < ITERATION_COUNT; k++) {
      pi += 1.0 / sixteenPowK * kthTerm(k);
      sixteenPowK *= 16;
    }
    return pi;
  }

  private static double kthTerm(final int k) {
    return 4.0 / (8.0 * k + 1) 
      - 2.0 / (8.0 * k + 4) 
      - 1.0 / (8.0 * k + 5) 
      - 1.0 / (8.0 * k + 6);
  }
}

I'd be curious to see a micro benchmark

like image 40
Andreas Avatar answered Oct 18 '25 08:10

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!