Recursive Chudnovsky Algorithm in Java -
i computer engineering student, , i've got project chudnovsky algorithm calculate pi, problem i've got decimal decimal(i mean if got length 3 it's going 3.14), have done code , 3.141592653589734
don't have idea how bit bit using recursive method.the code got far is
//this class implements interface contains method calcularpi public class chudnovsky_implements implements chudnovsky { public double calcularpi(int k)//this i'm trying bit bit i'm doing wrong. { if(k==0) return pi(k); else { double resultado= (pi(k))+(pi(k-1)); return resultado; } } public double pi(int k)//here calculated number pi constant k user give(k supposedly number of digits) { double numerador=(factorial(6*k)*((545140134*k)+13591409)); double denominador =(factorial(3*k)*math.pow(factorial(k), 3)*math.pow(-640320, (3*k))); double pi=(numerador/denominador); return pi; } public double factorial(int n)// class calculate factorial of number { if (n==0) return 1; else return n*(factorial(n-1)); }
if vague or don't quite understand english not main language sorry
with recursion:
package q46166389; public class chudnovsky { public static void main( string[ ] args ) { int k = 13; final string outputformat = "%." + ( k - 1 ) + "f"; double result = new chudnovsky( ).calculateloop( k ); // format output desired number of decimals system.out.println( "result = " + string.format( outputformat, result ) ); // or print it: system.out.println( "result = " + result ); result = 1 / new chudnovsky( ).calculaterecursive( k ); system.out.println( "result = " + string.format( outputformat, result ) ); system.out.println( "result = " + result ); } public double calculateloop( int k ) { double result = 0; ( int = 0; <= k; i++ ) { result = result + docalc( ); } return 1 / result; } public double calculaterecursive( int k ) { if ( k == 0 ) { return docalc( k ); } return docalc( k ) + calculaterecursive( k - 1 ); } public double docalc( int k ) { double numerator = math.pow( -1, k ) * factorial( 6 * k ) * ( 545140134 * k + 13591409 ); double denominator = factorial( 3 * k ) * math.pow( factorial( k ), 3 ) * math.pow( 640320, 3 * k + 3.0 / 2.0 ); return 12.0 * numerator / denominator; } public double factorial( int n ) { if ( n == 0 ) { return 1; } else { return n * factorial( n - 1 ); } } }
output:
result = 3.141592653590 result = 3.1415926535897936 result = 3.141592653590 result = 3.1415926535897936
please note answer works until k = 17 , have precision problems! if need more digits or more precision, need use bigdecimal
.
Comments
Post a Comment