For this program, I want to generate a floating point number in the interval [-1, 1] using the formular X(n+1) = (X(n) + X(n-1)) % 1.0, however, when I print out the numbers it generated, it printed out some number less than -1. The function I used here is fmod(), this function generate a random number between 0 to 1, then it is multiplied by 2 and minus 1, which should give me a floating number between -1 to 1.

The array for storing these random values are dynamically allocated using pointer.

I spent a lot of time fixing this but couldn't find out where the error is. Very appreciated if anyone can help. Thanks!!

Code:#include<stdio.h> #include<stdlib.h> #include<math.h> #define MAX_NUM 10 int main(int argc, char **argv) { float init_x1 = 0.122840678; float init_x2 = 0.102683; int i; int j; int count[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /* counter for histogram */ float *random_floating, *nodePtr; float *temp_x1; float *temp_x2; random_floating = (float *) malloc (MAX_NUM * sizeof(float)); /* allocate enough space for random number generated */ nodePtr = random_floating; *nodePtr++ = init_x1; *nodePtr++ = init_x2; for (; nodePtr < (MAX_NUM + random_floating); nodePtr++) { temp_x1 = nodePtr - 2; temp_x2 = nodePtr - 1; *nodePtr = fmod(*temp_x1 + *temp_x2, 1.0) * 2.0 - 1.0; /* generate a floating number in [-1, 1] */ printf ("%f\n", *nodePtr); count[(int)(*nodePtr * 10) + 10]++; } for (i = 0; i < 20; i++) printf ("%d ", count[i]); }