[英]How to use complex number "i" in C++
我現在正在編寫一個簡單的 DFT 算法,我想在復指數中使用復數 i。 我看到有人使用#include<complex>
和#include<cmath>
,然后他們使用了重載符號I
例如exp(2*I)
。 但它似乎在我的 Visual Studio 編譯器中不起作用。 那么,任何人都可以舉一個使用復指數的簡單例子嗎? 謝謝!
我最近也收到了這個問題,並為未來的讀者找到了一個簡單的方法:
只需使用<complex>
庫,如下所示
#include <iostream>
#include <complex>
using namespace std ;
int main(int argc, char* argv[])
{
const complex<double> i(0.0,1.0);
cout << i << endl ;
return(0) ;
}
這是一個簡短的完整示例:
#include <iostream>
#include <complex>
#include <cmath>
using namespace std;
typedef complex<double> dcomp;
int main() {
dcomp i;
dcomp a;
double pi;
pi = 2 * asin(1);
i = -1;
i = sqrt(i);
a = exp(pi*i) + 1.+0i;
cout << "i is " << i << "and Euler was right: exp(i pi) + 1 = " << a << endl;
}
用 g++ 測試
另一種方法是在 C++14 之后使用std::literals::complex_literals::operator""i
:
#include <iostream>
#include <complex>
int main() {
using namespace std::complex_literals;
auto c = 1.0 + 3.0i;
std::cout << "c = " << c << '\n';
}
輸出:
c = (1,3)
你可以在這里找到詳細信息
一個簡單的方法是
#include <complex>
using std::complex;
const double pi = 3.1415;
void foo()
{
complex<double> val(polar(1, pi/2.0); Create a complex from its olar representation
}
以下 C++ 代碼顯示了用於實現虛數 j 的宏。 眾所周知,在編程中,術語 i 和 j 通常用作計數器變量。 我改為使用大寫字母 J 來表示虛數以避免任何混淆。
/ * dcomplex.h
#ifndef DCOMPLEX_H_
#define DCOMPLEX_H_
#define J dcomplex(0.0,1.0)
typedef std::complex<double> dcomplex;
#endif /* DCOMPLEX_H_ */
使用這個宏,虛數 J [連同復數庫] 可以在主代碼中使用。 其使用示例如下所示:
....
....
#include <complex>
#include "dcomplex.h"
....
....
tmp = tmp + t[n]*exp( (2.0*PI*(double)n*(double)l/(double)tab_size)*J );
....
……
其中 tmp, t[n] 是復數類型的變量,J 是虛數。 變量 n、l 和 tab_size 是整數類型。 常數 PI 是眾所周知的常數 3.14... 函數 exp() 被重載以處理復數。 [nb 此代碼示例是簡單 DFT 的一部分]
使用此宏,代碼更具可讀性..
pi是一個無理數,不能用double精確表示。 pi 的不精確近似的cos可能會產生接近但可能不完全為 1 的結果。同樣, pi的不精確近似的不精確近似的sin會導致一個數字的量級非常小,即也許不完全是 0。為什么不將 I 定義為std::complex(0.0, 1.0)並避免無緣無故的不精確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.