正弦模式生成数据

时间:2013-04-10 02:12:17

标签: c++ visual-c++ visual-studio-2012

数据阵列(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;

}

1 个答案:

答案 0 :(得分:1)

您的rand()函数会生成0到RAND_MAX之间的随机数。

要使它在-0.5和0.5之间,你需要做这样的事情: rand() between 0 and 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);

  }

}