Domanda

Evening. I've got a question regarding base-16 computations in Java. I'm looking to compute pi with a reasonable algorithm to N digits with some constraint to the number of digits allowed (thinking something like 15-20). Eventually this will just be one function of a calculator later.

I'm not looking for ridiculous levels of precision, nor do I want help with the algorithm. I'm aware that there is a magic API method for it, but I'd rather do it myself.

The formula: Bailey–Borwein–Plouffe formula. From what I understand, it computes pi in hexadecimal.

So, what's my issue? I'm not that good at Java. The classes I've taken (up to and including Data Structures) really only used the languages I know as a means to an end, without focusing on anything language-specific. I want to compute pi to the nth digit in hexadecimal, then convert that value to a String for display purposes.

Any suggestions on where to start with that? My experience with coding in java is about 20 weeks, and what I'm stuck on seems to be a Java-specific thing.

If I'm wrong anywhere, by all means point it out. I'm here to learn.

È stato utile?

Soluzione

I would implement your current algorithim using BigDecimal first. When this works to your satisfaction you can look at replacing the functionality BigDecimal provides (assuming you want to write your own)

Altri suggerimenti

I am not sure exactly of what might help you but here is my suggestion. Since you're showing me a formula, you can use RECURSION instead of iteration with the while loop. Code example:

public static int series(int a, int b, int loopCount) {
    int sumTemp = a + b;
    b = sumTemp;

    loopCount--;
    if (loopCount > 0) {
        return series(a, b, loopCount);
    }
    else
    {
        return sumTemp;
    }
}

public static void main(String[] args) {
     int sum = series(5, 10, 3);
     System.out.println("Sum = " + sum);
}

Notes:

  • Notice the initial values of this simple formula is 5 and 10. Function series sums the 2 values in a loop.
  • In my series function, the new sum is stored into parameter b. This technique is forced upon me since Java passes by value, not reference.
  • Parameter loopCount keeps track of the loop #.
  • At the end, the variable sum is the returned value.

Lastly, use Math.pow function for the 16 to the power calculation. The class Math is quite useful for your studies.

Good luck,

Tommy Kwee

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top