Problem Description:
Two ways of calculating polynomial a0+a1*x+a2*x^2+a3*x^3+ .... (Common algorithm and Qin Jiushao algorithm) at a value of x, by calling the function tick in <time.h> (), calculate the time of the operation of the two methods, and derive ... See the following code for a predictable conclusion:
The code is as follows:
#include <stdio.h> #include <math.h>//pow#include<time.h>//tick#define maxoder 300//Maximum Order multiplier # define R EPEAT 1e5//function Repeat execution (time required for one execution is too short)//Common algorithm double multinomial_1 (int a[],int n,double x) {Double result = 0;int I;for (i=0;i< =n;++i) {result = result + A[i]*pow (x,i);//polynomial evaluation}return result;} Qin Jiushao algorithm double multinomial_2 (int a[],int n,double x) {Double result = 0;int I;for (i=n;i>0;--i) {result = A[i-1] + a[i]*pow (x,i);//polynomial evaluation: extracting common divisor}return result;} Calculates the time that the function was run once, void clock_t (start,clock_t end) {double duration; Store function Execution Time printf ("%f\n", (double) (End-start)); The Multinomial_1 function performs a dot duration = ((double) (end-start))/clocks_per_sec/repeat;//function executes the time required---clocks_per_ SEC hits printf per second ("%6.2e\n", duration);} int main () {int a[maxoder+1]; The coefficients for storing the polynomial double x; Original variable int i; Cyclic factor clock_t Start1; Record common function run the number of times clock_t end1; clock_t is the data type of the tick () function return value clock_t start2; Record Qin Jiushao algorithm function run number of times clock_t end2;for (i=0;i<=maxoder;++i)//initialization, coefficients of polynomial {a[i] = i;} Printf ("Please input a num:");//input Required value scanf ("%lf", &x); Note The format entered here is "%LF" instead of "%f"//Common algorithm start1 = Clock (); The number of times the function has been executed from the point of execution to this point for (i=0;i<repeat;i++) {multinomial_1 (a,maxoder,x);} End1 = Clock (); The number of times the function has been executed from the point of execution to this point//qin Jiushao algorithm start2 = Clock (); The number of times the function has been executed from the point of execution to this point for (i=0;i<repeat;i++) {multinomial_2 (a,maxoder,x);} End2 = Clock ();p rintf ("normal algorithm: \ n"), Time (START1,END1);p rintf ("qin Jiushao algorithm: \ n"); time (start2,end2); return 0;}
enter x=8 to see the results:
Conclusion: The efficiency of solving the problem is related to the merits of the algorithm
Multiple ways to calculate polynomial a0+a1*x+a2*x^2+a3*x^3+ .... (Computational efficiency and the importance of algorithms)