加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: abs(std :: complex)太慢了

发布时间:2020-12-16 10:37:59 所属栏目:百科 来源:网络整理
导读:为什么在一个大型复杂数组上运行std :: abs比使用sqrt和norm慢大约8倍? #include ctime#include cmath#include vector#include complex#include iostreamusing namespace std;int main(){ typedef complexdouble compd; vectorcompd arr(2e7); for (compd c
为什么在一个大型复杂数组上运行std :: abs比使用sqrt和norm慢大约8倍?

#include <ctime>
#include <cmath>
#include <vector>
#include <complex>
#include <iostream>
using namespace std;

int main()
{
    typedef complex<double> compd;

    vector<compd> arr(2e7);
    for (compd& c : arr)
    {
        c.real(rand());
        c.imag(rand());
    }

    double sm = 0;
    clock_t tm = clock();
    for (const compd& c : arr)
    {
        sm += abs(c);
    }
    cout << sm << ' ' << clock() - tm << endl; // 5.01554e+011 - 1640 ms

    sm = 0;
    tm = clock();
    for (const compd& c : arr)
    {
        sm += sqrt(norm(c));
    }
    cout << sm << ' ' << clock() - tm << endl; // 5.01554e+011 - 154

    sm = 0;
    tm = clock();
    for (const compd& c : arr)
    {
        sm += hypot(c.real(),c.imag());
    }
    cout << sm << ' ' << clock() - tm << endl; // 5.01554e+011 - 221
}

解决方法

我认为严格意义上的两者不应该被视为相同.

从cppreference on std::abs(std::complex)开始:

Errors and special cases are handled as if the function is implemented as std::hypot(std::real(z),std::imag(z))

也是从cppreference on std::norm(std::complex)开始:

The norm calculated by this function is also known as field norm or absolute square.

The Euclidean norm of a complex number is provided by std::abs,which is more costly to compute. In some situations,it may be replaced by std::norm,for example,if abs(z1) > abs(z2) then norm(z1) > norm(z2).

简而言之,存在从每个功能获得不同结果的情况.其中一些可能在std::hypot中找到.那里的注释还提到了以下内容:

std::hypot(x,y) is equivalent to std::abs(std::complex<double>(x,y))

通常,结果的准确性可能不同(由于通常的浮点混乱),并且似乎功能的设计尽可能准确.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读