2019年3月26日 星期二

2-10 定點迴路法 C語言求根

2-10 定點迴路法 C語言求根
Fixed-Point Iteration. Root finding.

Algorithm:

INPUT initial approximation p0; tolerance TOL; maximum number of iterations N0.
OUTPUT approximate solution p or message of failure.

Step 1 Set i=1.
Step 2 While i <= N0 do Steps 3-6.
Step 3 Set p=g(p0). (Compute pi.)
Step 4 If |p-p0|<tol mode="hold"> OUTPUT (p); (The procedure was successful.)
STOP.
Step 5 Set i=i+1.
Step 6 Set p0=p. (Update p0.)
Step 7 OUTPUT ('The method failed after N0 iterations, N0=', N0);
(The procedure was unsuccessful.)
STOP. 
程式
#include <stdio.h>
#include <math.h>

double f(double x)
{
return x*x*x*x-3*x*x-3;  //change equation for each problem
}

double g(double x)
{
return pow(3*x*x+3,.25);
}

int main()
{
    double p, p0, Tol;
    int i=1;
    int No;

    //printf("Enter approximate p: ");
    //scanf ("%lf", &p0);

    //printf("Desired Tolerance: ");
    //scanf ("%lf", &Tol);

    //printf("Maximum Iterations: ");
    //scanf ("%d", &No);
    scanf ("%lf %lf %d",&p0,&Tol, &No);

    while (i<=No)
    {
        p = g(p0);

        if((fabs(p-p0))<Tol)
        {
            //printf("%lf", &p);
            break;
        }
        printf("Iteration %d: Current value = %lf\n", i, p);

        i++;  //i=i+1
        p0=p;

        if (i>No)
        {
        printf("Method Failed after %d", No);
        printf(" iterations");
        }

    }

}

輸入資料
10.0 0.001 50
輸出結果
Iteration 1: Current value = 4.172157
Iteration 2: Current value = 2.725997
Iteration 3: Current value = 2.242595
Iteration 4: Current value = 2.062271
Iteration 5: Current value = 1.992422
Iteration 6: Current value = 1.965006
Iteration 7: Current value = 1.954192
Iteration 8: Current value = 1.949919
Iteration 9: Current value = 1.948229

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...