gpt4 book ai didi

c++ - std::abs(std::complex) 太慢

转载 作者:太空狗 更新时间:2023-10-29 19:42:59 29 4
gpt4 key购买 nike

为什么在大型复杂数组上运行 std::abs 比使用 sqrtnorm 慢大约 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))

一般来说,结果的准确性可能会有所不同(由于通常的浮点困惑),函数的设计似乎是为了尽可能准确。

关于c++ - std::abs(std::complex) 太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53518381/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com