• 求多项式的值,乘方函数


     1 #include <iostream>
    2 #include <time.h>
    3 #include <random>
    4 #include <iomanip>
    5 using namespace std;
    6
    7 //求指数函数
    8 inline double myPow(double x, int y)
    9 {
    10 unsigned int n;
    11
    12 //指数可能为负
    13 if (y >= 0)
    14 {
    15 n = y;
    16 }
    17 else
    18 {
    19 n = -y;
    20 }
    21
    22 //每次右移,相应x*=x,若当前最低位为1,则result *= x
    23 for (double result = 1; ; x *= x)
    24 {
    25 if ((n & 1) != 0)
    26 {
    27 result *= x;
    28 }
    29 if ((n >>= 1) == 0)
    30 {
    31 return (y >= 0)?result:1/result;//指数为负,取倒数
    32 }
    33 }
    34 }
    35 double polynomial(double a[], double x, int n)
    36 {
    37 double re = 0;
    38 for (int i = 0; i < n; i++)
    39 {
    40 re += a[i] * myPow(x, i);
    41 }
    42 return re;
    43 }
    44 double polynomial_horner(double a[], double x, int n)
    45 {
    46 double re = 0;
    47 for (int i = n - 1; i > 0; i--)
    48 {
    49 re = (a[i] + re) * x;
    50 }
    51 re += a[0];
    52 return re;
    53 }
    54 int main()
    55 {
    56 mt19937 eng;
    57 eng.seed((unsigned)time(NULL));
    58 uniform_real<double> unif;
    59 const size_t size = 10000;
    60 double *a = new double[size];
    61 for (int i = 0; i < size; i++)
    62 {
    63 a[i] = unif(eng);
    64 }
    65
    66 clock_t start = clock();
    67 cout << polynomial(a, 0.9, size) << endl;
    68 clock_t end = clock();
    69 double d = double(end - start)/CLOCKS_PER_SEC;
    70 cout << setprecision(4) << fixed << d << endl;
    71
    72 start = clock();
    73 cout.unsetf(ostream::floatfield);
    74 cout << polynomial_horner(a, 0.9, size) << endl;
    75 end = clock();
    76 d = double(end - start)/CLOCKS_PER_SEC;
    77 cout << setprecision(4) << fixed << d;
    78 }
  • 相关阅读:
    javascript关于继承
    javascript组合继承
    javascript创建对象的几种模式
    Angularjs学习笔记6_table1
    Angularjs学习笔记5_form1
    Angularjs学习笔记3_datepicker
    Angularjs学习笔记2_添加删除DOM元素
    Angularjs学习笔记5_scope和$rootScope
    Angularjs学习笔记1_基本技巧
    RabbitMQ基础概念
  • 原文地址:https://www.cnblogs.com/yysblog/p/2263491.html
Copyright © 2020-2023  润新知