RAND between 0 and 1

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fernando Barsoba

    RAND between 0 and 1

    Hi all,

    I think this has been posted many times.. but I tried several recipes
    for obtaining a random number between [0,1], but I can't make them work.

    So, does anyone know how to generate random number x, for 0<= x <=1??

    Thanks,

    FBM

    That's what I got.......

    float rndm = (float) (rand() / RAND_MAX);

    and I tried also

    float rndm = (float) (rand() % 2);

    with no success...
  • Skarmander

    #2
    Re: RAND between 0 and 1

    Fernando Barsoba wrote:[color=blue]
    > I think this has been posted many times.. but I tried several recipes
    > for obtaining a random number between [0,1], but I can't make them work.
    >
    > So, does anyone know how to generate random number x, for 0<= x <=1??
    >[/color]
    Question 13.16 in the FAQ: http://www.eskimo.com/~scs/C-faq/q13.16.html.
    Also check out the questions in the vicinity.

    S.

    Comment

    • Jack Klein

      #3
      Re: RAND between 0 and 1

      On Thu, 29 Sep 2005 03:51:13 GMT, Fernando Barsoba
      <fbarsoba@veriz on.net> wrote in comp.lang.c:
      [color=blue]
      > Hi all,
      >
      > I think this has been posted many times.. but I tried several recipes
      > for obtaining a random number between [0,1], but I can't make them work.[/color]

      Define what you mean by now working.
      [color=blue]
      > So, does anyone know how to generate random number x, for 0<= x <=1??
      >
      > Thanks,
      >
      > FBM
      >
      > That's what I got.......
      >
      > float rndm = (float) (rand() / RAND_MAX);[/color]

      Aha! Integer division! RAND_MAX is a macro that evaluates to a
      numeric literal of type int. rand() returns a value that is of type
      int. The result of dividing an int by an int is an int quotient, with
      any remainder discarded. Casting the result to a float after the
      integer division/truncation does not bring the fractional part back.
      [color=blue]
      > and I tried also
      >
      > float rndm = (float) (rand() % 2);
      >
      > with no success...[/color]

      In the future, don't just say "doesn't work". Describe the results
      you are getting. It makes no difference in this case, but very often
      it does when someone is trying to locate the cause of your problem.

      In any case, you need to cast one or the other of the operands of the
      division to a float. This will cause promotion of the other operand
      to a float. Then a float division will be performed on the two float
      values, yielding a float result. In any case, you do not need the
      cast on the assignment to a float, that conversion is automatic and
      the cast operator does absolutely nothing.

      float rndm = rand()/(float)RAND_MAX ;

      --
      Jack Klein
      Home: http://JK-Technology.Com
      FAQs for
      comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
      comp.lang.c++ http://www.parashift.com/c++-faq-lite/
      alt.comp.lang.l earn.c-c++

      Comment

      • Malcolm

        #4
        Re: RAND between 0 and 1


        "Fernando Barsoba" <fbarsoba@veriz on.net> wrote[color=blue]
        > float rndm = (float) (rand() / RAND_MAX);
        >[/color]
        This is the way to do it. However you need to cast to a float first,
        otherwise you will get an integer division.
        Incidentally it is traditional to divide by RAND_MAX plus one, because a lot
        of algorithms don't work as nicely when a random number on the interval 0-1
        is exactly unity.


        Comment

        • Martin Ambuhl

          #5
          Re: RAND between 0 and 1

          Fernando Barsoba wrote:[color=blue]
          > Hi all,
          >
          > I think this has been posted many times.. but I tried several recipes
          > for obtaining a random number between [0,1], but I can't make them work.
          >
          > So, does anyone know how to generate random number x, for 0<= x <=1??[/color]

          You could check the FAQ before posting. Or I could spoonfeed you:

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

          inline double closed_interval _rand(double x0, double x1)
          {
          return x0 + (x1 - x0) * rand() / ((double) RAND_MAX);
          }

          int main(void)
          {
          int pass;
          srand(time(0));
          for (pass = 0; pass < 10; pass++)
          printf("%d: %g\n", pass, closed_interval _rand(0, 1));
          return 0;
          }

          [output for one invocation]
          0: 0.589319
          1: 0.108868
          2: 0.13723
          3: 0.575189
          4: 0.444024
          5: 0.657485
          6: 0.83961
          7: 0.00479315
          8: 0.849472
          9: 0.740225

          Comment

          • Gaijinco

            #6
            Re: RAND between 0 and 1

            Is there any reason to avoid using this:

            srand(time(0));

            float random_number = rand();

            Comment

            • Gaijinco

              #7
              Re: RAND between 0 and 1

              Why is it better:

              rand() / (RAND_MAX / N + 1)

              than:

              srand(time(0));
              rand() % N;

              Comment

              • Fernando Barsoba

                #8
                Re: RAND between 0 and 1

                Thanks to all for your postings. I meant to say that the result was
                0.0.. but now I solved it thanks to your comments.[color=blue][color=green]
                >> float rndm = (rand() / (float)RAND_MAX );[/color][/color]

                The srand(time(null )) I used it to obtain a non-predictable random
                number generator (if i say it correctly..)

                cheers,

                FBM


                Fernando Barsoba wrote:[color=blue]
                > Hi all,
                >
                > I think this has been posted many times.. but I tried several recipes
                > for obtaining a random number between [0,1], but I can't make them work.
                >
                > So, does anyone know how to generate random number x, for 0<= x <=1??
                >
                > Thanks,
                >
                > FBM
                >
                > That's what I got.......
                >
                > float rndm = (float) (rand() / RAND_MAX);
                >
                > and I tried also
                >
                > float rndm = (float) (rand() % 2);
                >
                > with no success...[/color]

                Comment

                • Alexei A. Frounze

                  #9
                  Re: RAND between 0 and 1

                  "Gaijinco" <gaijinco@gmail .com> wrote in message
                  news:1127994671 .933852.250690@ z14g2000cwz.goo glegroups.com.. .[color=blue]
                  > Why is it better:
                  >
                  > rand() / (RAND_MAX / N + 1)
                  >
                  > than:
                  >
                  > srand(time(0));
                  > rand() % N;[/color]

                  The problem with random integers in a desired interval is that when you
                  start doing tricks like the above the distribution ceases to be uniform.
                  Here's an example revealing this problem:

                  #include <stdio.h>

                  #define MY_RAND_MAX 15 // my RAND_MAX for myrand()
                  #define N 10 // the N in myrand()%N
                  #define M 1000 // iterations count

                  // My fake rand() function,
                  // mimicking uniform distribution.
                  // THIS IS A BAD random generator,
                  // BUT A GOOD means to show the problem
                  // of the rand()%N approach to generate
                  // uniformly distributed numbers in the range
                  // smaller than [0,RAND_MAX].
                  int myrand()
                  {
                  static int seed = 0;
                  int res = seed;
                  // generate numbers in the range [0,MY_RAND_MAX]
                  // like so: 0,1,2,...,MY_RA ND_MAX-1,MY_RAND_MAX,0 ,1,2,...
                  if (++seed > MY_RAND_MAX)
                  seed = 0;
                  return res;
                  }

                  int main()
                  {
                  int i;
                  int aCnt[N];

                  // zero up counters of each of the numbers
                  // that will be generated at random:
                  for (i=0; i<N; i++)
                  aCnt[i] = 0;

                  // generate numbers at random and count
                  // how many time each of them was generated:
                  for (i=0; i<M; i++)
                  aCnt[myrand()%N]++;

                  // print out the statistics:
                  printf ("Statistics:\n "
                  "+--------+-------------------+\n"
                  "| Number | Times Encountered |\n"
                  "+--------+-------------------+\n");
                  for (i=0; i<N; i++)
                  printf ("| %-6d | %-17d |\n", i, aCnt[i]);
                  printf ("+--------+-------------------+\n");

                  return 0;
                  }


                  Alex


                  Comment

                  • Keith Thompson

                    #10
                    Re: RAND between 0 and 1

                    Fernando Barsoba <fbarsoba@veriz on.net> writes:[color=blue]
                    > Thanks to all for your postings. I meant to say that the result was
                    > 0.0.. but now I solved it thanks to your comments.[color=green][color=darkred]
                    > >> float rndm = (rand() / (float)RAND_MAX );[/color][/color]
                    >
                    > The srand(time(null )) I used it to obtain a non-predictable random
                    > number generator (if i say it correctly..)[/color]

                    Please don't top-post; your response goes below any quoted text, which
                    should be trimmed down to what's relevant.

                    I think you mean srand(time(NULL )). This isn't bad, but it does
                    assume some things that aren't guaranteed by the standard. The time()
                    function returns a result of type time_t, which is an arithmetic type
                    capable of representing times. It could legally be a floating-point
                    value in the range 0.0..1.0, which would result in always passing 0 to
                    srand(), which would always give you the same sequence of numbers. I
                    don't know of any implementations that behave this way, so that's
                    probably fairly safe. (srand() takes an argument of type unsigned
                    int, so the conversion from time_t isn't going to be a problem.)

                    Another problem is that the standard rand() function is often poorly
                    implemented. If the security of your system depends on high-quality
                    unpredictable random numbers (e.g., if you're doing cryptography), you
                    should find some system-specific random number generator. In
                    particular, using time() to seed the generator is good enough for some
                    applications, but could make it possible for an adversary to predict
                    the behavior of your program if he can guess what time it was started.

                    --
                    Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                    San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                    We must do something. This is something. Therefore, we must do this.

                    Comment

                    • James McIninch

                      #11
                      Re: RAND between 0 and 1

                      <posted & mailed>

                      float r = ((float) rand()) / RAND_MAX;

                      .... rand() returns and integer that is equal to or less than RAND_MAX.
                      Dividing an integer by an integer larger than it yields 0, if the same, 1.

                      Fernando Barsoba wrote:
                      [color=blue]
                      > Hi all,
                      >
                      > I think this has been posted many times.. but I tried several recipes
                      > for obtaining a random number between [0,1], but I can't make them work.
                      >
                      > So, does anyone know how to generate random number x, for 0<= x <=1??
                      >
                      > Thanks,
                      >
                      > FBM
                      >
                      > That's what I got.......
                      >
                      > float rndm = (float) (rand() / RAND_MAX);
                      >
                      > and I tried also
                      >
                      > float rndm = (float) (rand() % 2);
                      >
                      > with no success...[/color]

                      --
                      Remove '.nospam' from e-mail address to reply by e-mail

                      Comment

                      • websnarf@gmail.com

                        #12
                        Re: RAND between 0 and 1

                        Gaijinco wrote:[color=blue]
                        > Why is it better:
                        >
                        > rand() / (RAND_MAX / N + 1)
                        >
                        > than:
                        >
                        > srand(time(0));
                        > rand() % N;[/color]

                        Its not. See: http://www.azillionmonkeys.com/qed/random.html

                        --
                        Paul Hsieh
                        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.



                        Comment

                        Working...