Random Number Generator - Error

This is a discussion on Random Number Generator - Error within the C Programming forums, part of the General Programming Boards category; Hey guys. I know little about programming. I have made this code with some help, but there is still a ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Posts
    7

    Question Random Number Generator - Error

    Hey guys. I know little about programming. I have made this code with some help, but there is still a problem with it. I am basically trying to create a random number generator that will calculate the average of 1000 numbers and then go on and produce the average of square of those numbers, the cube, etc, up to power of 15. In this case I think I am missing a bracket around the j loop, but I am not sure where. Can anyone see it? I have to learn to really see the code through as well. Thank you.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main (int argc, char *argv[])
    {
    
      unsigned int iseed = (unsigned int)time(NULL);
      srand (iseed);
      int i,average; //defines i and average as integers
      int j;
      double x, y;
      double ran;
      double sum [15];
      for (i=0; i<15; i++)
         sum [i]=0;
      for (j=0; j<1000; j++)
    
    
      {
        //printf ("%u\n", rand ());
        x=y=(rand() / (RAND_MAX + 1.0));
        for (i=0; i<15; i++)     //error here averages less than 1
        sum[i]+=y;
        y=y*x;
    
      }
    printf("The Sum of Random Numbers : %d ", sum);
    for (i=0; i<15; i++)
    {
        average=sum[i]/j; //j values retained from the loop (1000); alternatively: sum[15]
        printf("The Average of Random Numbers : %d i=%d",average, i);
    }
    
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I don't understand the / RAND_MAX + 1

    Why not rand() % LargestNumberYouWant + 1?

  3. #3
    Registered User
    Join Date
    Sep 2010
    Posts
    7
    That's a separate issue, but it's because I don't know much about C. I use Code Blocks and used the help files to extract the format written there.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
        for (i=0; i<15; i++)     //error here averages less than 1
        sum[i]+=y;
        y=y*x;
    Since your indentation of subordinate code lines is missing, I can't tell for sure what you want here - but without braces around the y=y*x;, that line will execute just ONE time, instead of every time around the loop.

    Hope you learn to indent - your eye WILL become trained to use it, quite naturally.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    Quote Originally Posted by Adak View Post
    I don't understand the / RAND_MAX + 1

    Why not rand() % LargestNumberYouWant + 1?
    Because a real number in the range (0, 1] is required, and what's posted is the most straightforward way to do this.

    Yeah you want the line y=y*x; to be inside the loop otherwise it has no effect.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Sep 2010
    Posts
    7
    Could you be more specific about including y=y*x in the loop? I thought it is already in the loop.

  7. #7
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    1) You don' t need argc, argv (they are another "story" and have no use in this code).

    2) it is very complicated as you wrote it(for me).

    if you want take a look at this
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <math.h>
    #define size 5 //My code is for 5 numbers but you can easily change it
    
    int main (void){
    	int i, r, n=0, j, temp=0;
    	float sum=0;
    
    		srand(time(NULL));
    		for (i=1; i<=15; i++){
    			for(j=0; j<size; j++){
    				r = 0 + rand()%(size-0);
    				printf("Rand: %d\n", r);
    				//printf("i: %d\n", i);
    				temp =pow(r,i); // i use for my first time pow() and there  is a problem with i...if anyone else knows please tell
    				printf("temp: %d\n", temp);
    				sum = sum+r;
    				n++;
    			}
    		printf("Sum is: %f\n", sum);
    		printf("Average: %f\n", sum/n);
    		}
    			
      return 0;
    }
    i hope this is closer to what you want...
    Last edited by brack; 09-04-2010 at 05:21 PM.

  8. #8
    Registered User
    Join Date
    Sep 2010
    Posts
    7
    Ok, let's see if this makes it clear:

    I take 1000 random numbers between 0 and 1. I need two things from here:

    1. Generate the sum of all these numbers.
    2. Generate the AVERAGE of these numbers like this:

    a. First do a regular average: add up all 1000 numbers together and then divide by 1000.
    b. Now do the same, except SQUARE all the random numbers, add them up, and only then divide by 1000 to get the average.
    c. Do the same ...... except do the cube this time.
    ...
    ...
    ...
    continue like this until you hit the power of 15. So raise all of the random numbers to the power of 15 and then divide by 1000 again to get an average.

    Please note that the average in all these cases is going to be less than one because you're adding numbers that are less than one and get progressively smaller as you increase the power to which they are raised. This means that the generated output for the average must ALWAYS be smaller than 1, and get progressively smaller for larger and larger powers raised.

    Does this make sense?

    And thanks a lot brack. I will try to see if your code corrected what I was hoping. Meanwhile, if you think my explanation above changes things, I'd appreciate your advice.

    Thanks!

  9. #9
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    Quote Originally Posted by Adak View Post
    Code:
        for (i=0; i<15; i++)     //error here averages less than 1
        sum[i]+=y;
        y=y*x;
    Since your indentation of subordinate code lines is missing, I can't tell for sure what you want here - but without braces around the y=y*x;, that line will execute just ONE time, instead of every time around the loop.
    Explanation...
    Code:
    1)    for (i=0; i<15; i++){     //error here averages less than 1
    2)    sum[i]+=y;
    3)    y=y*x;
    4)    }
    without brances only the 2nd lne is inside the loop but as adam said you need both....
    i think this is what adam said
    // if i am wrong please correct me adam
    Last edited by brack; 09-04-2010 at 05:29 PM.

  10. #10
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    Quote Originally Posted by Excelisus View Post
    Ok, let's see if this makes it clear:

    I take 1000 random numbers between 0 and 1. I need two things from here:

    1. Generate the sum of all these numbers.
    2. Generate the AVERAGE of these numbers like this:

    a. First do a regular average: add up all 1000 numbers together and then divide by 1000.
    this cover some questions...now the only thing that remains is to understand how pow() works...
    Code:
    #include <stdio.h>
    
    #include <stdlib.h>
    
    #include <time.h>
    
    
    
    main(){
    
         int i;
    
         float x, sum=0, m;
    
    
    
                   srand(time(NULL));
    
                   for(i=0; i<1000; i++){
    
                        x = rand();
                        //printf("x: %f \n", x);
    
                        x = (x/RAND_MAX);
    
                        printf("x: %f \n", x);
    
                        sum+=x;
    
                   }
    
                   m=sum/1000;
    
                   printf("Average: %f\n", m);
    
    
    return 0;
    
    }

  11. #11
    Registered User
    Join Date
    Sep 2010
    Posts
    7
    I still haven't look at the code - I can't until I have access on my other computer when I can run the program + debugging mode. But basically the power portion is inherent in the loop itself. This is what x=x*y does.

    Basically first you have x. Then when the loop runs once more, you get x^2 just by the nature of the loop and definition. Then when the loop runs again this time x=x^2. Now when the program does x=x*y, the value becomes x=x^2*x which is the same as x^3. The loop continues like this until it reaches the power of 15 - which is what i<15 takes care of.

    So basically what you meant by your correction is this? I have to try this.

    Code:
      {
        //printf ("%u\n", rand ());
        x=y=(rand() / (RAND_MAX + 1.0));
    
    1)    for (i=0; i<15; i++){     //basically adding a bracket after this line
    2)    sum[i]+=y;
    3)    y=y*x;
    4)    }
    Ideally I would like to keep my own code with some modifications because that's what I understand best, even if barely. Otherwise I would have to start from scratch to understand a different code well enough.

  12. #12
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    Quote Originally Posted by Excelisus View Post
    Could you be more specific about including y=y*x in the loop? I thought it is already in the loop.
    If that were the case, how would you change the code to make it so that the y=y*x part was not inside the for-i loop any more?
    Stuck? That's because it is already is outside.

    Stick with the way you've written your program, it's fine, short of the small change with adding brackets. brack's code is wrong because it doesn't use the same random numbers for each power. He also either has no idea that you need real numbers in the range (0, 1], or doesn't understand how your code so simply does that. It's also more complicated than yours and far less efficient.

    BTW, you can shorten y = y * x to just y *= x
    Last edited by iMalc; 09-05-2010 at 12:58 AM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Excelisus View Post
    Could you be more specific about including y=y*x in the loop? I thought it is already in the loop.
    Code:
    1   for (i=0; i<15; i++)   
    2   sum[i]+=y;               
    3   y=y*x;
    I'm going to answer your question, but also go out on a bit of a limb here because I've never liked the "standard" (and totally non-obvious) way bracing is used in C.

    From the example above the loop is initiated on line 1 and correctly only executes line 2. Line 3 will not execute until the loop is complete. To include line 3 in the loop you need to put braces around it...
    Code:
    1    for (i= 0; i<15; i++){     
    2    sum[i]+=y;
    3    y=y*x;
    4    }
    ... like that. Now lines 2 and 3 will be included in the loop as a "statement block".

    My big grumble is the way this is formatted. It's not visually obvious where the loop begins and mismatched braces can be a frequent problem. I've always found the example below to be far more visually indicative of the code's function...
    Code:
    1    for (i = 0; i < 15; i++)   
    2       { sum[i] += y;
    3         y = y * x; }
    I know this is only text formatting but half of reading comprehension is in the way the text is presented... The block of code is now visually obvious. Of course this is how I format my own code

    Just a pet peeve...
    Last edited by CommonTater; 09-05-2010 at 07:44 AM.

  14. #14
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,409
    Quote Originally Posted by CommonTater
    I'm going to answer your question, but also go out on a bit of a limb here because I've never liked the "standard" (and totally non-obvious) way bracing is used in C.
    That sounds like a "strawman complaint" because you compared an example of "standard" (or rather, a common convention of) brace placement with no indentation versus an example of "non-standard" brace placement but with indentation. If we add indentation:
    Code:
    for (i= 0; i<15; i++){
        sum[i]+=y;
        y=y*x;
    }
    then your complaint about it being "not visually obvious where the loop begins and mismatched braces can be a frequent problem" is no longer valid, or at least as valid as a complaint against your personal style.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  15. #15
    Registered User
    Join Date
    Aug 2010
    Posts
    230
    Quote Originally Posted by iMalc View Post
    brack's code is wrong because it doesn't use the same random numbers for each power.
    BTW, you can shorten y = y * x to just y *= x
    You' re right....i wasn' t thinking something like that...my sorry

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. random number guessing game
    By kazoo in forum C Programming
    Replies: 7
    Last Post: 05-30-2010, 11:31 AM
  2. Simple XOR Program
    By dolfaniss in forum C Programming
    Replies: 8
    Last Post: 05-24-2010, 01:27 PM
  3. random number generator help
    By mayoussa89 in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2010, 07:26 AM
  4. adding a number to a number
    By bigmac(rexdale) in forum C Programming
    Replies: 11
    Last Post: 10-24-2007, 12:56 PM
  5. random number between negative and positive number
    By anomaly in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2003, 07:40 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21