2013-04-10 31 views
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; 

} 
+0

你有什麼看起來不錯......你能更具體的噪音如何不正確顯示? – maditya 2013-04-10 02:19:57

+1

另外,剛剛注意到你的兩條if語句是賦值:'save ='y'' - 你想要'save =='y'' – maditya 2013-04-10 02:22:17

+0

你沒有正確使用rand()函數......查看我的回答 – maditya 2013-04-10 02:28:55

回答

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); 

    } 

} 
+0

感謝maditya的評論 – Mac 2013-04-11 00:35:44