-2

Total noob here. Can someone give me an example on how i can generate a 2kHz sine wave array with white noise of variance 0.01 in C? This is what I have so far:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define PI 3.141592653589793

int main() {
    int i;
    double buffer[10000];

    for(i = 0; i < 10000; i++)
    {
        buffer[i] = sin(2000 * (2 * PI) * i / 6000) + sqrt(0.01)rand;
    }

    return 0;
}
rwar
  • 3
  • 1
  • 4
  • And what is the problem with the code you have? – Some programmer dude Sep 19 '15 at 17:27
  • not sure how to add the white noise with the rand function :S – rwar Sep 19 '15 at 17:29
  • (Except for the missing random seed and the typos at sqrt(0.01)rand) – Peter Goldsborough Sep 19 '15 at 17:29
  • Well you would certainly have to seed your random number generator with srand((unsigned)time(0)), and the sqrt(0.01)rand should probably be sqrt(0.01) * rand()? – Peter Goldsborough Sep 19 '15 at 17:30
  • what do you mean by "seed your random number generator with srand((unsigned)time(0))"? – rwar Sep 19 '15 at 17:32
  • How about reading the man pages for `rand` and `srand`? Too complicated? – too honest for this site Sep 19 '15 at 17:35
  • A random-number-generator will not be random unless you give it a different start/seed value each time you call it (rand isn't magic, it's just an algorithm that does fancy things given an input to output almost-random values). Before you use rand() in your program, you have to call srand() once with a unique value. Because time doesn't stop that often it's a good idea to pass it the number of seconds since the epoch. But that information really is out there, so see here for example: http://stackoverflow.com/questions/822323/how-to-generate-a-random-number-in-c – Peter Goldsborough Sep 19 '15 at 17:36
  • one thing though, when i print out the results from "buffer array", i get huge values. what I'm trying to do is replicate this matlab code into c: x = sin(2*pi*(2000)*(0:1/6000:100)); signal = x + sqrt(0.01)*(randn(size(x)); – rwar Sep 19 '15 at 22:14

1 Answers1

0

(For reference)

You first have to seed the random-number generator using srand(), to which you should pass a unique value at every program-run.

Your code, modified for correctness:

#include <math.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand((unsigned)time(NULL));

    int i;
    double buffer[10000];

    for(i = 0; i < 10000; i++)
    {
        buffer[i] = sin(2000 * (2 * M_PI) * i / 6000) + sqrt(0.01) * rand();
    }

    /* ... */

    return 0;
}
Peter Goldsborough
  • 1,366
  • 16
  • 20