Waveform periods
For a school assignment I had to write a program that outputs the data for a single sine wave period.
I used Gnuplot to plot the data, and I added the option to output Sawtooth, square and triangle just because i thought it was educational.
#define NUM_OF_PERIODS 2 // sets the number of periods
#define NUM_OF_HARMONICS 250 // sets the number of harmonics for the sawtooth
int F = 480;
int SR = 48000;
int length = (SR / (F/NUM_OF_PERIODS));
float amp = 1;
double y;
int x;
Sinewave:
for(x = 0; x <= length; x++)
{
double fundamental = (sin(x*2*M_PI*F/SR));
y = fundamental;
cout << x << "\t" << y << endl;
}
Sawtooth:
for(x = 0; x <= length; x++)
{
double fundamental = (sin(x*2*M_PI*F/SR)); // fundamental sine
for(int i = 2; i <= NUM_OF_HARMONICS; i++)
{
fundamental = (fundamental + ((amp/i)*(sin(x*2*M_PI*(F*i)/SR)))); //adds harmonics to the fundamental sinewave
y = fundamental;
}
cout << x << "\t" << y << endl;
}
Squarewave:
for(x = 0; x <= length; x++)
{
double fundamental = (sin(x*2*M_PI*F/SR)); // fundamental sine
for(int i = 3; i <= 79; i += 2) // + 2 for odd harmonics only
{
fundamental = (fundamental + ((amp/i)*(sin(x*2*M_PI*(F*i)/SR)))); //adds odd harmonics to the fundamental sinewave
y = fundamental;
}
cout << x << "\t" << y << endl;
}
Trianglewave:
for(x = 0; x <= length; x++)
{
double fundamental = (sin(x*2*M_PI*F/SR)); // fundamental sine
int t = -1;
for(int i = 3; i <= 127; i += 2)
{
fundamental = fundamental + ( (pow(t,(i /2))*(amp/pow(i, 2)))*(sin(x*2*M_PI*(F*i)/SR)));
//adds odd harmonics with amplitude 1/(harmonic^2) to the fundamental sinewave,
y = fundamental;
}
cout << x << "\t" << y << endl;
}