I am trying to convert a C code to java, it's the Newton Raphson algorithm implementation. All is going well but there is a problem of pointers which were used in C code and i have removed them in java. The C code part is:
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));
}
and the function definition is something like this:
double newton(double x_0, double error, int max_iters,
int* iters_p, int* converged_p)
Now the problem is that, the values of two pointer variables are just zero every time. Also the if(converged) shows an error message of incomoatible types. required boolean, found int. Below is the java code so please help overcome this.
//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);
}
}