多项式求和算法对比

#include
#include
#include
#include
#include
#include


double getSum1(double x_, int n_, double nums[]);
double getSum2(double x_, int n_, double nums[]);

clock_t time1;
clock_t time2;
clock_t time3;

int main() {

	// 测试多项式的和
	// f(x) = a1 + a2*x +a3*x^2 + ... + an*x^(n-1)
	/*
	srand(unsigned(time(NULL)));
	int randomize(void);
	int a = rand() % 50;
	printf("a: %d\n", a);
	*/

	int n = 10;
	double x = 3.1;
	int run_Cycle = 1000000;
	double nums[10] = {};
	
	for (int i = 0; i < n; i++) {
		nums[i] = (double)(rand() % 10);
		//printf("number %d: %d\n", i, nums[i]);
	}

	time1 = clock();
	double result1;
	for (int i = 0; i < run_Cycle; i++) {
		result1 = getSum1(x, n, nums);
	}
	
	time2 = clock();
	printf("ticks1 %f\n", (double)(time2 - time1));
	printf("function a takes %6.2e s, result = %f\n", (double)(time2-time1)/CLOCKS_PER_SEC/run_Cycle, result1);

	double result2;
	for (int i = 0; i < run_Cycle; i++) {
		result2 = getSum2(x, n, nums);
	}
	time3 = clock();
	printf("ticks2 %f\n", (double)(time3 - time2));
	printf("function b takes %6.2e s, result = %f\n", (double)(time3 - time2)/CLOCKS_PER_SEC/run_Cycle, result2);

	_getch();
	return 0;
}

// 加号前各项相加
double getSum1(double x, int n, double nums[]) {

	double sum = 0;
	for (int i = 0; i < n; i++) {
		sum += (pow(x, i) * nums[i]);
	}
	
	return sum;
}

// 提取公因式算法
double getSum2(double x, int n, double nums[]) {

	double p = nums[n - 1];
	for (int i = n - 2; i >= 0; i--) {
		p = p * x + nums[i];
	}

	return p;
}

你可能感兴趣的:(学习,算法)