'Gaussian random noise (complex number in C++)

I want to generate random noise in c++. The code that I am using is

int N=8;    
double N0=5; 
complex<double> NoiseVec[N]; 
complex<double> t;    


for(int i=0; i<N ;i++){
NoiseVec[i] = (complex<double> t(rand(),rand()));
}

but it is giving me error. I am not sure where the mistake is

c++


Solution 1:[1]

The mistake is here:

NoiseVec[i] = (complex<double> t(rand(),rand()));

I believe you want to create a temporary and assign it to NoiseVec[i]; if so, you should change it to:

NoiseVec[i] = complex<double>(rand(), rand());

Edit0: Also,

int N=8;
complex<double> NoiseVec[N];

is not standard C++, even though clang and GCC compile it.

I suggest you use a range-based for loop:

#include <complex>
#include <cstdlib>

// Don't do this
//using namespace std;

int main() {
    std::complex<double> NoiseVec[8];
    for (auto& noiseElem : NoiseVec)
        noiseElem = std::complex<double>(std::rand(), std::rand());
}

Edit1: As per Sebastian's comment: to obtain Gaussian random noise, you should use std::normal_distribution instead of std::rand().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1