rand() between m and n

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gary Wessle

    rand() between m and n


    Hi

    I need help to generate some random numbers between 2 and 8.

    #include <cstdlib>
    using std::rand;

    the following was out of my range,

    int main() {

    for (int i = 0; i < 50; i++){
    int x = (int(rand())/444489786)*8;
    cout << x << '\t' << endl;
    }
    }

    it can be any quality random number.


    thanks

  • Marco Wahl

    #2
    Re: rand() between m and n

    Gary Wessle <phddas@yahoo.c omwrites:
    I need help to generate some random numbers between 2 and 8.
    So you need random numbers out of 3, 4, 5, 6, 7, right?
    the following was out of my range,
    Did you get all zeros?
    int main() {
    >
    for (int i = 0; i < 50; i++){
    int x = (int(rand())/444489786)*8;
    cout << x << '\t' << endl;
    }
    }
    >
    it can be any quality random number.
    So the rand function should suffice.

    Converting the result of the rand function to float
    allows you to normalize the rand result into the
    interval [0, 1] as floating point number. Then you can
    multiply with five (you want to pick a number from a
    range of five numbers, don't you?) and then round and
    add three to the result.

    For some code example see e.g.




    HTH
    --
    Marco Wahl

    Comment

    • Gernot Frisch

      #3
      Re: rand() between m and n

      I need help to generate some random numbers between 2 and 8.
      >
      #include <cstdlib>
      using std::rand;
      >
      the following was out of my range,
      >
      int main() {
      >
      for (int i = 0; i < 50; i++){
      int x = (int(rand())/444489786)*8;
      cout << x << '\t' << endl;
      }
      }
      // return random number elm[from; upto]
      int rnd_range( int from, int upto)
      {
      return (rand() % (upto - from + 1)) + from;
      }




      Comment

      • Chris Theis

        #4
        Re: rand() between m and n


        "Gernot Frisch" <Me@Privacy.net wrote in message
        news:4j8kd7F6qo 0lU1@individual .net...
        >
        >I need help to generate some random numbers between 2 and 8.
        >>
        >#include <cstdlib>
        >using std::rand;
        >>
        >the following was out of my range,
        >>
        >int main() {
        >>
        > for (int i = 0; i < 50; i++){
        > int x = (int(rand())/444489786)*8;
        > cout << x << '\t' << endl;
        > }
        >}
        >
        // return random number elm[from; upto]
        int rnd_range( int from, int upto)
        {
        return (rand() % (upto - from + 1)) + from;
        }
        >
        This works absolutely fine, but still the other approach using a random
        number between r out of [0,1) ( x = Min + r * (Max-Min) ) is favorable
        because it doesn't tamper with the "randomness " of the generator and has no
        influence on the period of the generated sequence.

        Cheers
        Chris


        Comment

        • Gary Wessle

          #5
          Re: rand() between m and n

          "Chris Theis" <christian.thei s@nospam.cern.c hwrites:
          "Gernot Frisch" <Me@Privacy.net wrote in message
          news:4j8kd7F6qo 0lU1@individual .net...
          I need help to generate some random numbers between 2 and 8.
          >
          #include <cstdlib>
          using std::rand;
          >
          the following was out of my range,
          >
          int main() {
          >
          for (int i = 0; i < 50; i++){
          int x = (int(rand())/444489786)*8;
          cout << x << '\t' << endl;
          }
          }
          // return random number elm[from; upto]
          int rnd_range( int from, int upto)
          {
          return (rand() % (upto - from + 1)) + from;
          }
          >
          This works absolutely fine, but still the other approach using a random
          number between r out of [0,1) ( x = Min + r * (Max-Min) ) is favorable

          do you mean
          int x = from + rand() * (to-from) ?
          because it doesn't tamper with the "randomness " of the generator and has no
          influence on the period of the generated sequence.
          Cheers
          Chris

          I am not sure what wrong I am doing, followed the link provided by
          Marco, which was


          the following puts out zeros on my screen. only zeros no mater how
          many times I run it.

          #include <ctime>
          using std::time;


          int main() {

          int x;
          const int N = 100;
          srand( static_cast<uns igned(time( NULL )) );
          for (int i = 0; i < 4; i++) {
          x = static_cast<int ( N*rand())/(RAND_MAX+1) ;
          cout << x << endl;
          }
          }

          Comment

          • Marcus Kwok

            #6
            Re: rand() between m and n

            Gary Wessle <phddas@yahoo.c omwrote:
            I am not sure what wrong I am doing, followed the link provided by
            Marco, which was

            >
            the following puts out zeros on my screen. only zeros no mater how
            many times I run it.
            #include <iostream>
            #include <ctime>
            using std::time;
            using std::cout;
            int main() {
            >
            int x;
            const int N = 100;
            srand( static_cast<uns igned(time( NULL )) );
            for (int i = 0; i < 4; i++) {
            x = static_cast<int ( N*rand())/(RAND_MAX+1) ;
            Let's rearrange your spacing:

            x = static_cast<int >(N*rand()) / (RAND_MAX+1);

            So, you are taking the value of N*rand(), and then casting it to an int.
            Then you are dividing it by (RAND_MAX+1), which is also an int.
            Therefore you have an int/int, so the division truncates, resulting in a
            zero.

            I would try casting the result of N*rand() to a double, then performing
            the (floating-point) division, then casting THAT result to an int:

            x = static_cast<int >(static_cast<d ouble>(N*rand() ) / (RAND_MAX+1));

            Of course, you could break this up into smaller steps.
            cout << x << endl;
            }
            }
            --
            Marcus Kwok
            Replace 'invalid' with 'net' to reply

            Comment

            • Gary Wessle

              #7
              Re: rand() between m and n

              ricecake@gehenn om.invalid (Marcus Kwok) writes:
              Gary Wessle <phddas@yahoo.c omwrote:
              I am not sure what wrong I am doing, followed the link provided by
              Marco, which was


              the following puts out zeros on my screen. only zeros no mater how
              many times I run it.
              >
              #include <iostream>
              >
              #include <ctime>
              using std::time;
              >
              using std::cout;
              >
              int main() {

              int x;
              const int N = 100;
              srand( static_cast<uns igned(time( NULL )) );
              for (int i = 0; i < 4; i++) {
              x = static_cast<int ( N*rand())/(RAND_MAX+1) ;
              >
              Let's rearrange your spacing:
              >
              x = static_cast<int >(N*rand()) / (RAND_MAX+1);
              >
              So, you are taking the value of N*rand(), and then casting it to an int.
              Then you are dividing it by (RAND_MAX+1), which is also an int.
              Therefore you have an int/int, so the division truncates, resulting in a
              zero.
              >
              I would try casting the result of N*rand() to a double, then performing
              the (floating-point) division, then casting THAT result to an int:
              >
              x = static_cast<int >(static_cast<d ouble>(N*rand() ) / (RAND_MAX+1));
              >
              Of course, you could break this up into smaller steps.
              >
              cout << x << endl;
              }
              }
              >
              --
              Marcus Kwok
              Replace 'invalid' with 'net' to reply

              do you mean this, it still puts out all zeros, could you try it on
              your machine and report back? thanks


              *************** *
              *************** *
              #include <iostream>
              #include <cstdlib>

              using namespace std;

              int main() {

              srand( static_cast<uns igned(time( NULL )) );
              int N = 8;
              int x;
              for (unsigned i=0; i<5; i++){
              x = static_cast<int >(static_cast<d ouble>(N*rand() ) / (RAND_MAX+1));
              cout << x << '\t';
              }
              }
              *************** *
              *************** *

              Comment

              • Marco Wahl

                #8
                Re: rand() between m and n

                Gary Wessle <phddas@yahoo.c omwrites:
                do you mean this, it still puts out all zeros, could you try it on
                your machine and report back? thanks
                >
                >
                #include <iostream>
                #include <cstdlib>
                >
                using namespace std;
                >
                int main() {
                >
                srand( static_cast<uns igned(time( NULL )) );
                int N = 8;
                int x;
                for (unsigned i=0; i<5; i++){
                x = static_cast<int >(static_cast<d ouble>(N*rand() ) / (RAND_MAX+1));
                cout << x << '\t';
                }
                }
                I checked and also get all 0s. The output looks more interesting when using the line

                x = static_cast<int >(N * static_cast<dou ble>(rand()) / (static_cast<do uble>(RAND_MAX) + 1));

                There is an overflow on my machine at least when calculating RAND_MAX+1.


                HTH
                --
                Marco Wahl

                Comment

                • arash.koushkestani@gmail.com

                  #9
                  Re: rand() between m and n

                  Hello all,
                  why you are going far away?
                  first use srand() to randomize radom number, srand get a parameter as
                  seed, like:
                  srand(3); or you can use srand(time(0));
                  then use this method to have randome number in a certain range:
                  x=minum number +rand()% maximum number;
                  for example: x=1+rand()%6; gives you a random number between 1 to 6;
                  Also you mist use srand() before using rand, you can use it at the
                  first of main()
                  Hope I could help you;

                  Comment

                  • Gary Wessle

                    #10
                    Re: rand() between m and n

                    the thing is if you need to generate say 5 random numbers between 2
                    and 8 then this will not work, run this

                    for (int i= 0; i< 5; i++){
                    srand( time( 0));
                    int x= 2+ rand() %8;
                    cout << x << '\n';
                    }

                    Comment

                    • Kai-Uwe Bux

                      #11
                      Re: rand() between m and n

                      Gary Wessle wrote:
                      the thing is if you need to generate say 5 random numbers between 2
                      and 8 then this will not work, run this
                      >
                      for (int i= 0; i< 5; i++){
                      srand( time( 0));
                      int x= 2+ rand() %8;
                      int x = 2 + rand() % 6;
                      cout << x << '\n';
                      }

                      Best

                      Kai-Uwe Bux

                      Comment

                      • Gary Wessle

                        #12
                        Re: rand() between m and n

                        Marco Wahl <mw@visenso.dew rites:
                        Gary Wessle <phddas@yahoo.c omwrites:
                        >
                        do you mean this, it still puts out all zeros, could you try it on
                        your machine and report back? thanks


                        #include <iostream>
                        #include <cstdlib>

                        using namespace std;

                        int main() {

                        srand( static_cast<uns igned(time( NULL )) );
                        int N = 8;
                        int x;
                        for (unsigned i=0; i<5; i++){
                        x = static_cast<int >(static_cast<d ouble>(N*rand() ) / (RAND_MAX+1));
                        cout << x << '\t';
                        }
                        }
                        >
                        I checked and also get all 0s. The output looks more interesting when using the line
                        >
                        x = static_cast<int >(N * static_cast<dou ble>(rand()) / (static_cast<do uble>(RAND_MAX) + 1));
                        >
                        There is an overflow on my machine at least when calculating RAND_MAX+1.
                        >
                        >
                        HTH
                        --
                        Marco Wahl
                        http://visenso.com
                        here is the final code for future readers.

                        *************** *************** *************** *************** ****
                        int randam(int from, int to) {
                        int f = from;
                        int t = to;
                        int a = to-from+1;
                        return static_cast<int (a * static_cast<dou ble>(rand())/
                        (static_cast<do uble>(RAND_MAX) + 1))+from;
                        }

                        int main() {

                        // print out 5 random numbers between 2 and 8
                        srand( static_cast<uns igned(time( NULL )) );
                        for(int i=0; i<5; i++) cout << randam(2,8) << " ";

                        }

                        Comment

                        • Chris Theis

                          #13
                          Re: rand() between m and n

                          "Gary Wessle" <phddas@yahoo.c omwrote in message
                          news:874pwveb1o .fsf@localhost. localdomain...
                          Marco Wahl <mw@visenso.dew rites:
                          >
                          >Gary Wessle <phddas@yahoo.c omwrites:
                          >>
                          do you mean this, it still puts out all zeros, could you try it on
                          your machine and report back? thanks
                          >
                          >
                          #include <iostream>
                          #include <cstdlib>
                          >
                          using namespace std;
                          >
                          int main() {
                          >
                          srand( static_cast<uns igned(time( NULL )) );
                          int N = 8;
                          int x;
                          for (unsigned i=0; i<5; i++){
                          x = static_cast<int >(static_cast<d ouble>(N*rand() ) /
                          (RAND_MAX+1));
                          cout << x << '\t';
                          }
                          }
                          >>
                          >I checked and also get all 0s. The output looks more interesting when
                          >using the line
                          >>
                          >x = static_cast<int >(N * static_cast<dou ble>(rand()) /
                          >(static_cast<d ouble>(RAND_MAX ) + 1));
                          >>
                          >There is an overflow on my machine at least when calculating RAND_MAX+1.
                          >>
                          >>
                          >HTH
                          >--
                          >Marco Wahl
                          >http://visenso.com
                          >
                          here is the final code for future readers.
                          >
                          *************** *************** *************** *************** ****
                          int randam(int from, int to) {
                          int f = from;
                          int t = to;
                          int a = to-from+1;
                          return static_cast<int (a * static_cast<dou ble>(rand())/
                          (static_cast<do uble>(RAND_MAX) + 1))+from;
                          }
                          >
                          int main() {
                          >
                          // print out 5 random numbers between 2 and 8
                          srand( static_cast<uns igned(time( NULL )) );
                          for(int i=0; i<5; i++) cout << randam(2,8) << " ";
                          >
                          }
                          Hi Gary,
                          do you mean int x = from + rand() * (to-from) ?
                          Yes, that's what I mean. It a simple scaling and adding an offset to the
                          result of a random number in the [0,1).

                          The code above should give you what you are looking for. In a more compact
                          form you can write it like this:

                          return static_cast<int >( from + ( (to - from) * (rand() / (RAND_MAX +
                          1.0)) ));

                          But be careful - the statement above is different than writing

                          return static_cast<int >( from + ( (to - from) * (rand() / (RAND_MAX +
                          1)) ));

                          The "beast" that you were running into was the integer division of rand() by
                          another much larger integer. The result of this integer devision is always 0
                          and that's why you obtained zeros (or the offset from). However, by using
                          1.0 instead of 1 in the calculation you implicitly convert the divisor to a
                          float and consequently the division is performed and results in a float.

                          HTH
                          Chris


                          Comment

                          • Chris Theis

                            #14
                            Re: rand() between m and n


                            <arash.koushkes tani@gmail.comw rote in message
                            news:1154507129 .015574.198850@ h48g2000cwc.goo glegroups.com.. .
                            Hello all,
                            why you are going far away?
                            first use srand() to randomize radom number, srand get a parameter as
                            seed, like:
                            srand(3); or you can use srand(time(0));
                            then use this method to have randome number in a certain range:
                            x=minum number +rand()% maximum number;
                            Yes, that surely works but brings back my original comment. Using the modulo
                            operation you interfere with the randomness and don't make use of the full
                            period of the random generator. Anyway, it depends on your application
                            whether this matters or not.

                            Cheers
                            Chris


                            Comment

                            • Kai-Uwe Bux

                              #15
                              Re: rand() between m and n

                              Chris Theis wrote:
                              >
                              <arash.koushkes tani@gmail.comw rote in message
                              news:1154507129 .015574.198850@ h48g2000cwc.goo glegroups.com.. .
                              >Hello all,
                              >why you are going far away?
                              >first use srand() to randomize radom number, srand get a parameter as
                              >seed, like:
                              >srand(3); or you can use srand(time(0));
                              >then use this method to have randome number in a certain range:
                              >x=minum number +rand()% maximum number;
                              >
                              Yes, that surely works but brings back my original comment. Using the
                              modulo operation you interfere with the randomness
                              How, and why?
                              and don't make use of the full period of the random generator.
                              Huh? I see that that can happen. However, I do not see why the alternative
                              of chopping [0,RAND_MAX] into n intervals of equal length it a priory
                              better.

                              As far as I can see, any kind of mapping N values to n < N values can tamper
                              with the period or other measures of randomness. Whether a particular
                              mapping fares better or worse depends on the underlying random number
                              generator.

                              Anyway, it depends on your application whether this matters or not.
                              True, and I think up-thread it was stated that quality does not matter.


                              Best

                              Kai-Uwe Bux

                              Comment

                              Working...