我正在尝试将 C 代码转换为 java,它是 Newton Raphson 算法实现。一切进展顺利,但存在 C 代码中使用的指针问题,我已在 java 中删除了它们。C代码部分是:
x = newton(x_0, error, max_iters, &iters, &converged); //Call to a function (newton)
if (converged) {
printf("Newton algorithm converged after %d steps.\n", iters);
printf("The approximate solution is %19.16e\n", x);
printf("f(%19.16e) = %19.16e\n", x, f(x));
} else
{
printf("Newton algorithm didn't converge after %d steps.\n",
iters);
printf("The final estimate was %19.16e\n", x);
printf("f(%19.16e) = %19.16e\n", x, f(x));
}
函数定义是这样的:
double newton(double x_0, double error, int max_iters,
int* iters_p, int* converged_p)
现在的问题是,两个指针变量的值每次都为零。if(converged) 还显示了不兼容类型的错误消息。必需的布尔值,找到 int。下面是java代码,所以请帮助克服这个问题。
//Member Functions///////
public
double function( double x)
{
return x*x - 2;
}
double F_Deriv( double x )
{
return 2.0*x;
}
double newton(double x_0, double error, int max_iters,int iters, int converged)
{
double x = x_0;
double x_prev;
int iter = 0;
do {
iter++;
x_prev = x;
x = x_prev - function(x_prev)/F_Deriv(x_prev);
}
while (Math.abs(x - x_prev) > error && iter < max_iters);
if (Math.abs(x - x_prev) <= error)
converged = 1;
else
converged = 0;
iters = iter;
return x;
}
/////Main Function///////
public static void main(String[] args) {
Newton_Raphson obj=new Newton_Raphson();
Scanner input=new Scanner(System.in);
double x_0; /* Initial guess */
double x; /* Approximate solution */
double error; /* Maximum error */
int max_iters; /* Maximum number of iterations */
int iters; /* Actual number of iterations */
int converged; /* Whether iteration converged */
System.out.println( "Enter Initial Solution: " );
x_0=input.nextDouble();
System.out.println( "Enter Error: " );
error=input.nextDouble();
System.out.println( "Enter Maximum Iterations: " );
max_iters=input.nextInt();
x = obj.newton(x_0, error, max_iters, iters, converged);
if(converged)
{
System.out.println("Newton algorithm converged after "+ iters +" steps.");
System.out.println("The approximate solution is "+ x);
}
else
{
System.out.println("Newton algorithm didn't converge after " + iters + " steps.");
System.out.println("The final estimate was " + x);
}
}