gpt4 book ai didi

java - Java中的递归Chudnovsky算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:12:43 24 4
gpt4 key购买 nike

我是一名计算机工程专业的学生,​​我有一个项目要做,即使用 Chudnovsky 算法来计算 Pi,但我遇到的问题是逐个十进制计算(我的意思是如果有长度 3 它将是 3.14),我已经完成了执行此操作的代码并得到 3.141592653589734 但我不知道如何使用递归方法一点一点地完成它。The到目前为止我得到的代码是

 //This class implements an interface which only contains the method calcularPi
public class Chudnovsky_Implements implements Chudnovsky {


public double calcularPi(int k)//This is where I'm trying to do it bit by bit which I'm probably doing it wrong.
{
if(k==0)
return Pi(k);
else {
double resultado= (Pi(k))+(Pi(k-1));
return resultado;

}

}

public double Pi(int k)//Here i calculated the number Pi with a constant k that the user give(k is supposedly to be the 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)// This is a class to calculate an factorial of a number
{
if (n==0)
return 1;
else
return n*(factorial(n-1));
}

如果有什么地方有点含糊或者你不太明白英语不是我的主要语言抱歉

This is the integer the teacher gave to us

最佳答案

递归:

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 the output to the desired number of decimals
System.out.println( "result = " + String.format( outputFormat, result ) );
// Or just 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;
for ( int i = 0; i <= k; i++ ) {
result = result + doCalc( i );
}
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 );
}
}

}

输出:

result = 3.141592653590
result = 3.1415926535897936
result = 3.141592653590
result = 3.1415926535897936

请注意,此答案仅在 k = 17 之前有效,并且存在精度问题!如果您需要更多位数或更高的精度,则需要使用 BigDecimal

关于java - Java中的递归Chudnovsky算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46166389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com