1. 程式人生 > 其它 >計算給定多項式在給定點x 處的值

計算給定多項式在給定點x 處的值

計算給定多項式在給定點\(x\)處的值

方法1

\[f(x)=a_0+a_1x+\cdots+a_{n-1}x^{n-1}+a_nx^n \]
double f_1(int n, double a[], double x) {
    int i;
    double p = a[0];
    for (i = 1; i <= n; i++)
        p += (a[i] * pow(x, i));
    return p;

}

方法2

多項式可以拆成如下形式:

\[f(x)=a_0+x(a_1+x(\cdots(a_{n-1}+x(a_n))\cdots) \]
double f_2(int n, double a[], double x) {
    int i;
    double p = a[n];
    for (i = n; i > 0; i--)
        p = a[n - 1] + x * p;
    return p;
}

計算給定多項式\(f(x)=\sum_{i=0}^9i\cdot x^i\)在給定點\(x=1.1\)處的值\(f(1.1)\)

#include <stdio.h>
#include <time.h>
#include <math.h>

#define MAXK 1e7
#define MAXN 10
clock_t start, stop;
double duration;

double f_1(int n, double a[], double x) {
    int i;
    double p = a[0];
    for (i = 1; i <= n; i++)
        p += (a[i] * pow(x, i));
    return p;

}

double f_2(int n, double a[], double x) {
    int i;
    double p = a[n];
    for (i = n; i > 0; i--)
        p = a[n - 1] + x * p;
    return p;
}


void compute_time(double function(), int n, double a[], double x) {
    start = clock();
    for (int i = 0; i < MAXK; i++)
        function(n, a, x);
    stop = clock();
    duration = ((double) (stop - start)) / CLK_TCK / MAXK;
    printf("Duration: %.2e s\n", duration);
}

int main(void) {
    double a[MAXN];
    compute_time(f_1, MAXN - 1, a, 1.1);
    compute_time(f_2, MAXN - 1, a, 1.1);
    return 0;
}

執行結果:

第二種方法比第一種方法快一個數量級