#include <iostream>
#include <random>
#include <vector>
using namespace std;
double vector_mul_funtion_1(const vector<double>& data, double x, size_t n) {
int64_t start_time = clock();
long i;
double result = data[0];
double xpower = x;
for (i = 1; i < n; ++i) {
result += data[i] * xpower;
xpower = xpower * x;
}
double used_time = 1.0 * (clock() - start_time) / CLOCKS_PER_SEC;
printf("vector_mul_funtion_1 deal n = [%lld] need time [%f] second\n", n, used_time);
return result;
}
double vector_mul_funtion_2(const vector<double>& data, double x, size_t n) {
int64_t start_time = clock();
long i;
double result = data[n - 1];
for (i = n - 2; i >= 0; --i) {
result = data[i] + x * result;
}
double used_time = 1.0 * (clock() - start_time) / CLOCKS_PER_SEC;
printf("vector_mul_funtion_2 deal n = [%lld] need time [%f] second\n", n, used_time);
return result;
}
void vector_mul_test() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(0, 1);
size_t n = 5e7 + 7;
vector<double> data(n, 0);
for (size_t i = 0; i < n; ++i) {
data[i] = dist(gen);
}
double x = dist(gen);
printf("start\n");
double y1 = vector_mul_funtion_1(data, x, n);
double y2 = vector_mul_funtion_2(data, x, n);
printf("y1 = [%f]; y2 = [%f]; y1 == y2 = [%d]\n", y1, y2, y1 == y2);
double y3 = vector_mul_funtion_2(data, x, n);
double y4 = vector_mul_funtion_1(data, x, n);
printf("y3 = [%f]; y4 = [%f]; y3 == y4 = [%d]\n", y3, y4, y3 == y4);
}
int main() {
vector_mul_test();
return 0;
}