-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathch1_polysum.cpp
More file actions
62 lines (50 loc) · 1.06 KB
/
ch1_polysum.cpp
File metadata and controls
62 lines (50 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Example program
#include <math.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
float f1(int n, float a[], float x)
{
int i;
float p = a[0];
for (i=0; i<=n; ++i)
{
p += ( a[i] * pow(x,i) );
}
return p;
}
float f2(int n, float a[], float x)
{
int i;
float p = a[n];
for (i=n; i>0; --i)
{
p = x*p + a[i-1];
}
return p;
}
int main()
{
int n = 10000000;
float* a = (float *) malloc(sizeof(float)*(n+1));
// init a
for (int j=0; j<=n; ++j)
a[j] = (float)j*0.01;
float x = 1.0001;
time_t begin, end;
float spent1, spent2;
begin = clock();
float r1 = f1(n, a, x);
end = clock();
spent1 = (float)(end-begin) / CLOCKS_PER_SEC;
begin = clock();
float r2 = f2(n, a, x);
end = clock();
spent2 = (float)(end-begin) / CLOCKS_PER_SEC;
printf("result1 = %f\n", r1);
printf("result2 = %f\n", r2);
printf("time spent1 = %f\n", spent1);
printf("time spent2 = %f\n", spent2);
free(a);
return 0;
}