• 多项式求和算法对比


    1. #include<stdio.h>
    2. #include<conio.h>
    3. #include<random>
    4. #include<windows.h>
    5. #include<time.h>
    6. #include<math.h>
    7. double getSum1(double x_, int n_, double nums[]);
    8. double getSum2(double x_, int n_, double nums[]);
    9. clock_t time1;
    10. clock_t time2;
    11. clock_t time3;
    12. int main() {
    13. // 测试多项式的和
    14. // f(x) = a1 + a2*x +a3*x^2 + ... + an*x^(n-1)
    15. /*
    16. srand(unsigned(time(NULL)));
    17. int randomize(void);
    18. int a = rand() % 50;
    19. printf("a: %d\n", a);
    20. */
    21. int n = 10;
    22. double x = 3.1;
    23. int run_Cycle = 1000000;
    24. double nums[10] = {};
    25. for (int i = 0; i < n; i++) {
    26. nums[i] = (double)(rand() % 10);
    27. //printf("number %d: %d\n", i, nums[i]);
    28. }
    29. time1 = clock();
    30. double result1;
    31. for (int i = 0; i < run_Cycle; i++) {
    32. result1 = getSum1(x, n, nums);
    33. }
    34. time2 = clock();
    35. printf("ticks1 %f\n", (double)(time2 - time1));
    36. printf("function a takes %6.2e s, result = %f\n", (double)(time2-time1)/CLOCKS_PER_SEC/run_Cycle, result1);
    37. double result2;
    38. for (int i = 0; i < run_Cycle; i++) {
    39. result2 = getSum2(x, n, nums);
    40. }
    41. time3 = clock();
    42. printf("ticks2 %f\n", (double)(time3 - time2));
    43. printf("function b takes %6.2e s, result = %f\n", (double)(time3 - time2)/CLOCKS_PER_SEC/run_Cycle, result2);
    44. _getch();
    45. return 0;
    46. }
    47. // 加号前各项相加
    48. double getSum1(double x, int n, double nums[]) {
    49. double sum = 0;
    50. for (int i = 0; i < n; i++) {
    51. sum += (pow(x, i) * nums[i]);
    52. }
    53. return sum;
    54. }
    55. // 提取公因式算法
    56. double getSum2(double x, int n, double nums[]) {
    57. double p = nums[n - 1];
    58. for (int i = n - 2; i >= 0; i--) {
    59. p = p * x + nums[i];
    60. }
    61. return p;
    62. }

  • 相关阅读:
    线段树的区间修改
    笙默考试管理系统-MyExamTest----codemirror(31)
    旧版elasticsearch 2.3.4 集群部署过程
    如何快速提升教育直播间人气
    torch.nn.DataParallel类
    01 uniapp/微信小程序 项目day01
    c语言---19函数的调用
    深入URP之Shader篇16: UNITY_BRANCH和UNITY_FLATTEN
    jmeter接口自动化测试
    random生成随机数的灵活运用
  • 原文地址:https://blog.csdn.net/adaadadsa/article/details/126915038