1

数据数组(0>359deg)=相位+((正弦值*增益+-归一化为增益噪声值)+偏差)

y=(G x sin(θ+φ)+-N)+偏置

这就是我到目前为止所拥有的。由于某种原因,在 Excel 中设置图表时,噪音无法正确显示。

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <ctime> // convert time value to string
#include <cstdlib>  // standard general utilities library "# generator"
#include <fstream>  // writing data to disk

using namespace std;

#pragma warning(disable:4996)

int _tmain(int argc, _TCHAR* argv[])

{

srand((unsigned)time(0));

// declarations
FILE *fptr;
char fileName[50] = "";
double freq;
double gain;
double phase;
double bias;
double rand_noise = ((double)rand()/ ((RAND_MAX)) - 0.5); 
char save;
double noise;

const long double PI = acos((long double) -1);


// user inputs for sine wave values

cout<<"Enter Frequency: [1-10Mhz] ";
cin>>freq;
cout<<"Enter Gain of Sine Wave: [1-10] ";
cin>>gain;
cout<<"Enter Phase Angle: [0-180] ";
cin>>phase;
cout<<"Enter Bias (offset) [+/- 10] ";
cin>>bias;
cout<<"Enter % Noise level introduced to sine (percent) [0 - 100%] ";
cin>>noise;
cout<<"Do you want to save the data [y/n]: ";
cin>>save;


if (save == 'y'){
cout<<"Enter a file name you wish to use: ";
    cin>> fileName;
}


double timeint = (double)1/freq/360;
long double interval = (2*PI)/360;
long double sinevalue;
if (save == 'y') {
sprintf(fileName, "%s.csv", fileName);
fptr = fopen(fileName, "w");
fprintf(fptr, "%s,", "Time(1/f)");
fprintf(fptr, "%s\n", "Sine Pattern");
}

for(int i=0; i<=360; i++){
sinevalue = (gain*sin((interval*i)+phase)+(rand_noise*(noise/100)*gain))+bias;
if (save == 'y') {
    fprintf(fptr, "%f,", timeint*i);
    fprintf(fptr, "%f\n", sinevalue);

}

}

return 0;

}
4

1 回答 1

1

您的rand()函数会生成一个介于 0 和RAND_MAX之间的随机数。

要使其介于 -0.5 和 0.5 之间,您需要执行以下操作: rand() 介于 0 和 1 之间

#include <cstdlib>

//...
for(int i=0; i<=360; i++){

  double rand_noise = ((double)rand()/ ((RAND_MAX)) - 0.5; //divide rand() by RAND_MAX to get between 0 and 1, then subtract 0.5 to be between -0.5 and 0.5.
  sinevalue = (gain*sin((interval*i)+phase)+(rand_noise*(noise/100)*gain))+bias;

  if (save == 'y') {
    fprintf(fptr, "%f,", timeint*i);
    fprintf(fptr, "%f\n", sinevalue);

  }

}
于 2013-04-10T02:23:27.883 回答