bigdecimal - Million elements of PI in Java BBP formula -
i try implement bbp formula calculating milion elements of pi. have problem calculating , displaying results. when set i
1 000 000
in loop , mathcontext()
more 1000
program not ending. paste code below, please help.
import java.math.bigdecimal; import java.math.mathcontext; import java.math.roundingmode; public class rsi { public static void main(string[] args) { bigdecimal iterationresult, temp, temp2, temp3, temp4, temp5, one, two, four, five, six, eight, sixteen, ii, result, pd, tc; result = new bigdecimal(0); result.setscale(1000000, roundingmode.half_down); (int = 0; < 1000000; i++) { pd = new bigdecimal(0); tc = new bigdecimal(0); temp = new bigdecimal(0); temp2 = new bigdecimal(0); temp3 = new bigdecimal(0); temp4 = new bigdecimal(0); temp5 = new bigdecimal(0); 2 = new bigdecimal(2); 4 = new bigdecimal(4); 5 = new bigdecimal(5); 6 = new bigdecimal(6); 8 = new bigdecimal(8); sixteen = new bigdecimal(16); 1 = new bigdecimal(1); iterationresult = new bigdecimal(0); ii = new bigdecimal(i); // calculate 1/16^i temp = one.divide((sixteen.pow(i)), new mathcontext(10, roundingmode.half_down)); // calculate 4/(8*i+1) first word temp2 = four.divide((eight.multiply(ii)).add(one), new mathcontext( 1000, roundingmode.half_down)); // calculate 2/(8*i+4) second word temp3 = two.divide((eight.multiply(ii)).add(four), new mathcontext( 1000, roundingmode.half_down)); // calculate 1/(8*i+5) third word temp4 = one.divide(((eight.multiply(ii)).add(five)), new mathcontext(1000, roundingmode.half_down)); // calculate 1/(8*i+6) fourth word temp5 = one.divide(((eight.multiply(ii)).add(six)), new mathcontext(1000, roundingmode.half_down)); // calculate ( 4/(8*i+1) )-( 2/(8*i+4) ) first - second pd = temp2.subtract(temp3); // calculate -third-fourth word tc = (temp4.negate()).subtract(temp5); // calculate 1/16^k * ((first - second) + (-third - fourth)) iterationresult = temp.multiply((pd.add(tc))); result = result.add(iterationresult); } system.out.println("result " + result); } }
why can't display 1 million of digits when set loop 1 million , mathcontext
million too?
the problem computer slow compute it. difficulty of task grows (probably n^3
), if takes around 1 second compute 1 000
digits, take billion seconds compute 1 000 000
digits. apparently such tasks computed using heavily optimized code , using computational clusters. guess, bbp formula work better if use specially crafted data type performs intermediate computations in hexadecimal , convert decimal @ end print result. way 1/16^i
step trivial. bigdecimal
java type not optimal such computations.
Comments
Post a Comment