sine wave generation in c++
Solution 1
taking into the formula of sine wave:
y(t) = A * sin(2 * PI * f * t + shift)
where:
A = the amplitude, the peak deviation of the function from zero.
f = the ordinary frequency, the number of oscillations (cycles)
t = time
shift = phase shift
would be:
y[t] = AMPLITUDE * sin (2 * M_PI * 0.15 * t + 0) + ZERO_OFFSET;
^^^ f = 15 cycles / NUM_POINTS = 0.15 Hz
To have one full-cycle, loop from y[0:t)
where t
is the time or number of points it takes to have a full cycle (i.e. wavelength)
Solution 2
It appears you need 100 samples for one cycle, so you probably need this:
...
#define _USE_MATH_DEFINES
#include <math.h>
...
#define NB_OF_SAMPLES 100
...
double angle = 0.0;
for (int i = 0; i < NB_OF_SAMPLES; i++)
{
outfile << int(3276 * sin(angle) + 32767) << "\n";
angle += (2 * M_PI) / NB_OF_SAMPLES;
}
...
Or better:
#define NB_OF_SAMPLES 100
#define OFFSET 3276
#define AMPLITUDE 32767
...
double angle = 0.0;
for (int i = 0; i < NB_OF_SAMPLES; i++)
{
outfile << int(AMPLITUDE * sin(angle) + OFFSET) << "\n";
angle += (2 * M_PI) / NB_OF_SAMPLES;
}
...
Solution 3
A full cycle consists of 360 degrees. samples needed is 100.
So step size is 3.6
int main()
{
ofstream outfile;
outfile.open("data.dat",ios::trunc | ios::out);
for(int i=0;i<101;i++)
{
float rads = M_PI/180;
outfile << (float)(3276*sin(3.6*i*rads)+32767) << endl;
}
outfile.close();
return 0;
}
If number of samples is 200, then step size if 360/200 = 1.8
int main()
{
ofstream outfile;
outfile.open("data.dat",ios::trunc | ios::out);
for(int i=0;i<201;i++)
{
float rads = M_PI/180;
outfile << (float)(3276*sin(1.8*i*rads)+32767) << endl;
}
outfile.close();
return 0;
}
Output:
Pradeep
Updated on July 11, 2020Comments
-
Pradeep almost 4 years
I am trying to generate a set of points, which when plotted as a graph represent a sine wave of 1 cycle. The requirements are :
- a sine wave of 1 cycle
- lower limit = 29491
- upper limit = 36043
- no of points = 100
- Amplitude = 3276
- zero offset = 32767
Code :
int main() { ofstream outfile; outfile.open("data.dat",ios::trunc | ios::out); for(int i=0;i<100;i++) { outfile << int(3276*sin(i)+32767) << "\n"; } outfile.close(); return 0; }
I am generating and storing the points in a file. When these points are plotted I get the following graph.
But I only need one cycle. How can I do this?
- a sine wave of 1 cycle
-
underscore_d almost 6 years
/i
er, no. You mean* (i / 100.0)
. I mean, the 1st iteration of what you wrote is instant UB! -
Some programmer dude almost 6 yearsPlease note that
M_PI
is not a standard macro, not all libraries define it. -
Paul Floyd almost 6 years@Some programmer dude Have you ever used a compiler/library that didn't have it easily available?
-
Some programmer dude almost 6 yearsI have seen it missing somewhere, but it was some time ago. However, considering that it's included with the MSVC headers and mandated by POSIX it's almost (but not quite) universal.