Program for Fixed Point Iteration Method using Java Programming Language
Algorithm of fixed point Iteration method
1
2
3
4
5
6
7
8
|
Step 1. Start the program.
Step 2. Define the function x = φ(x).
Step 3. Enter the initial guess of the root, say x0.
Step 4. Calculate y0 = φ(x0).
Step 5. If |x0 – y0| < ϵ, a prescribed accuracy, then go to step 7.
Step 6. Let x0 = y0 and go to step 4.
Step 7. Print the value of x0.
Step 8. Stop the program.
|
/* ex2-9.java is used for solving nonlinear equation
* based on Fixed-Point Algorithm g(x)=x with initial
* approximation P0.
*/
public class Main {
double f(double x1) {
return (Math.cos(x1)-3*x1+1);
}
double g(double x1) {
return ( (1+Math.cos(x1))/ 3 );
}
public static void main(String args[]){
Main fun = new Main();
final int MAX = 20; /* maximum iterations */
final double TOL =0.00001;/* maximum iterations */
int i=1;
int step=1, N=10;
double x0, x1, e;
x0=1.0;
N=10;
e=0.00001;
/* Implementing Fixed Point Iteration */
System.out.printf("\nStep\tx0\t\t f(x0)\t\tx1\t\t f(x1)\n");
do {
x1 = fun.g(x0);
System.out.printf("%d\t%f\t%f\t%f\t%f\n",step, x0, fun.f(x0), x1, fun.f(x1));
step = step + 1;
if(step>N) {
System.out.printf("Not Convergent.");
break;
}
x0 = x1;
}while( Math.abs(fun.f(x1)) > e);
System.out.printf("\nRoot is %f", x1);
}
}
輸出畫面
Step x0 f(x0) x1 f(x1)
1 1.000000 -1.459698 0.513434 0.330761
2 0.513434 0.330761 0.623688 -0.059333
3 0.623688 -0.059333 0.603910 0.011391
4 0.603910 0.011391 0.607707 -0.002162
5 0.607707 -0.002162 0.606986 0.000411
6 0.606986 0.000411 0.607124 -0.000078
7 0.607124 -0.000078 0.607097 0.000015
8 0.607097 0.000015 0.607102 -0.000003
Root is 0.607102
沒有留言:
張貼留言