How to generate random numbers in C

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

    #1

    How to generate random numbers in C

    I need to generate two uniform random numbers between 0 and 1 in C ?
    How to do it ?

    I looked into rand function where you need to #define RAND_MAX as 1
    but will this rand function give me uniformly distributed and unique
    numbers ?
  • user923005

    #2
    Re: How to generate random numbers in C

    On Apr 10, 9:54 pm, pereges <Brol...@gmail. comwrote:
    I need to generate two uniform random numbers between 0 and 1 in C ?
    How to do it ?
    If you have modern hardware and IEEE floating point, I recommend
    dsfmt:

    otherwise WELL512a.c and WELL512a.h from here:
    http://www.iro.umontreal.ca/~panneton/WELLRNG.html

    Are another possibility.
    I looked into rand function where you need to #define RAND_MAX as 1
    but will this rand function give me  uniformly distributed and unique
    numbers ?
    That is a read-only value for you. It's not something that you set,
    it is something that you inquire upon.

    Comment

    • osmium

      #3
      Re: How to generate random numbers in C

      "pereges" writes:
      >I need to generate two uniform random numbers between 0 and 1 in C ?
      How to do it ?
      >
      I looked into rand function where you need to #define RAND_MAX as 1
      but will this rand function give me uniformly distributed and unique
      numbers ?
      There is useful information in the FAQ starting at about 13.15



      A set of numbers shouldn't be random AND unique. One of the important
      properties of a random number generator is that numbers can be repeated. To
      provide what I understand you to want, look into "shuffle" as described in
      13.19


      Comment

      • Richard Tobin

        #4
        Re: How to generate random numbers in C

        In article <9cfa5c82-298d-4fd1-b2d0-44a31a004120@s3 3g2000pri.googl egroups.com>,
        pereges <Broli00@gmail. comwrote:
        >I looked into rand function where you need to #define RAND_MAX as 1
        RAND_MAX tells you what the maximum random number is. It doesn't
        let you control it.
        >but will this rand function give me uniformly distributed and unique
        >numbers ?
        >I need to generate two uniform random numbers between 0 and 1 in C ?
        rand() returns an integer between 0 and RAND_MAX. It's intended
        to be uniformly distributed (though the standard doesn't seem to
        say so) so you can get uniformly distributed random floating-point
        numbers by something like

        ((double)rand() ) / RAND_MAX

        If you really need *unique* random numbers you're going to have to
        do something more complicated. Are you sure you really do?

        -- Richard
        --
        :wq

        Comment

        • pereges

          #5
          Re: How to generate random numbers in C

          what about drand48() function ? Is this included in C standard ?

          Comment

          • Joachim Schmitz

            #6
            Re: How to generate random numbers in C

            pereges wrote:
            what about drand48() function ? Is this included in C standard ?
            Why not reading it yourself? At least the drafts are available at no charge,
            the latest is to be found at


            But no, drand48 is not mentioned there. I believe it is POSIX.

            Bye, Jojo


            Comment

            • Paul Hsieh

              #7
              Re: How to generate random numbers in C

              On Apr 10, 9:54 pm, pereges <Brol...@gmail. comwrote:
              I need to generate two uniform random numbers between 0 and 1 in C ?
              How to do it ?
              >
              I looked into rand function where you need to #define RAND_MAX as 1
              but will this rand function give me uniformly distributed and unique
              numbers ?
              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.


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


              Comment

              • Gordon Burditt

                #8
                Re: How to generate random numbers in C

                >I need to generate two uniform random numbers between 0 and 1 in C ?

                Computers do not generate truly random numbers without hardware support.
                Some techniques include the detection of radioactive decay and thermal
                noise from a reverse-biased diode. There is some belief that there
                is randomness in the timing (say, down to picoseconds) of keystrokes,
                although I don't think anyone has managed to tie human typing to quantum
                effects yet. Some CPU chips have hardware for random number generation
                on them.

                You may want pseudo-random numbers. In cryptography, random numbers
                are very important and the difference between pseudo-random numbers
                and real random numbers used in encryption may get you killed as a
                spy.

                If you try to offer casino gambling games (e.g. craps, blackjack,
                roulette, etc.) for real money using pseudo-random numbers, you're
                going to lose.

                rand() returns the same sequence of numbers each time the program
                starts up unless you call srand() with a different seed value from
                the last time. Seed values are commonly derived from the time and/or
                process ID (but NOT in applications where real random numbers are needed,
                like gambling or cryptography: 32 bits of randomness isn't enough, and
                a poor seed can cripple a good random number generator).
                >How to do it ?
                There are better pseudo-random number generators than rand().
                These have the disadvantage that they are not included in all C
                libraries.
                >I looked into rand function where you need to #define RAND_MAX as 1
                You do not get to redefine RAND_MAX. Also, the return type of rand()
                is int, so don't expect any values where 0 < rand() < 1 . If RAND_MAX
                were 1 (not allowed by the standard) all you would get is 0 and 1.
                >but will this rand function give me uniformly distributed and unique
                >numbers ?
                Consider using algebra. rand() returns [0, RAND_MAX]. You want
                numbers between 0.0 and 1.0 including both endpoints. Or is that just
                including 0.0 but not 1.0? Consider what these might give you:

                ((double)rand() )/RAND_MAX
                or
                ((double)rand() )/(RAND_MAX+1)

                Comment

                • Malcolm McLean

                  #9
                  Re: How to generate random numbers in C

                  "pereges" <Broli00@gmail. comwrote in message news:
                  >I need to generate two uniform random numbers between 0 and 1 in C ?
                  How to do it ?
                  >
                  I looked into rand function where you need to #define RAND_MAX as 1
                  but will this rand function give me uniformly distributed and unique
                  numbers ?
                  >
                  No, defining RAND_MAX as something else won't help. All it will do is make
                  the identifier useless in the rest of your program, without touching the
                  random number generator. Strictly it is UB in case RAND_MAX appears in some
                  standard library macro or other.

                  This is the generally accpeted way to do it
                  #define uniform() (rand() / (RAND_MAX + 1.0))
                  #define rnd(x) ( (x) * uniform() )

                  we add 1.0 to make rand() never return exactly unity, so rnd() is always in
                  the range 0 to x-1.

                  --
                  Free games and programming goodies.



                  Comment

                  • Bill Reid

                    #10
                    Re: How to generate random numbers in C


                    user923005 <dcorbit@connx. comwrote in message
                    news:df327012-0f05-4d7f-9cf0-06e0ec18af95@u6 9g2000hse.googl egroups.com...
                    On Apr 11, 12:20 pm, gordonb.k5...@b urditt.org (Gordon Burditt) wrote:
                    If you try to offer casino gambling games (e.g. craps, blackjack,
                    roulette, etc.) for real money using pseudo-random numbers, you're
                    going to lose.
                    There is no mathematical basis for this general statement, however,
                    there have been cases where people caught on to the sequence coming
                    from a poorly- or non-reseeded pseudo-random number generator
                    in a casino game and won hundreds of $thousands before the
                    casino realized their error...
                    The most important factor in gambling is the size of the house.
                    There is also no mathematical basis for THIS statement...you
                    guys are batting .000 again...
                    In a fair game, the player with the biggest house money volume wins.
                    Oh, a "fair game"...who the hell offers a "fair game"? In any event,
                    it's irrelevant, because the actual most important factor (to the extent
                    that we indulge in the pointless semantics of pronouncing a "most
                    important factor") is the "expectatio n" of the game.
                    Assuming a Markov process (random walk) the players will get ahead and
                    behind in a random, wobbling fashion. But as soon as the cash for one
                    player is gone, the game is over. If you have one hundred dollars and
                    the opponent has one trillion dollars, you are in a lot of trouble.
                    If you have a casino, and are stupidly offering a "fair game"
                    (0% "expectatio n"), you will eventually lose all your $trillion
                    to salaries and other expenses no matter how many individual
                    players come in and lose $100, because the money you win
                    from them will be offset by players who "get lucky" and win
                    $100, $200, $3000, or more...

                    You would be correct if you asserted that there is relationship
                    between the size of your "bankroll" and your average bet size
                    as a fraction of that "bankroll" in terms of actually acheiving
                    a result of "bankroll" growth (or non-loss) that conforms to
                    your "expectatio n" for the game. But that's a slightly more
                    complicated concept, innit?
                    That's why I call gambling "A tax on stupidity."
                    Stupidity is kind of its own tax, innit?

                    ---
                    William Ernest Reid



                    Comment

                    • Ben Bacarisse

                      #11
                      Re: How to generate random numbers in C

                      "Malcolm McLean" <regniztar@btin ternet.comwrite s:
                      "pereges" <Broli00@gmail. comwrote in message news:
                      >>I need to generate two uniform random numbers between 0 and 1 in C ?
                      >How to do it ?
                      >>
                      >I looked into rand function where you need to #define RAND_MAX as 1
                      >but will this rand function give me uniformly distributed and unique
                      >numbers ?
                      >>
                      No, defining RAND_MAX as something else won't help. All it will do is
                      make the identifier useless in the rest of your program, without
                      touching the random number generator. Strictly it is UB in case
                      RAND_MAX appears in some standard library macro or other.
                      >
                      This is the generally accpeted way to do it
                      #define uniform() (rand() / (RAND_MAX + 1.0))
                      #define rnd(x) ( (x) * uniform() )
                      >
                      we add 1.0 to make rand() never return exactly unity, so rnd() is
                      always in the range 0 to x-1.
                      rnd(m) can be much closer to m than m-1. Did you mean:

                      #define rnd(x) ((int)((x) * uniform()))

                      perhaps? The OP wanted numbers between 0 and 1 so your uniform() is
                      sufficient if they mean doubles in [0,1).

                      --
                      Ben.

                      Comment

                      • Gordon Burditt

                        #12
                        Re: How to generate random numbers in C

                        If you try to offer casino gambling games (e.g. craps, blackjack,
                        roulette, etc.) for real money using pseudo-random numbers, you're
                        going to lose.
                        >
                        >There is no mathematical basis for this general statement, however,
                        >there have been cases where people caught on to the sequence coming
                        >from a poorly- or non-reseeded pseudo-random number generator
                        >in a casino game and won hundreds of $thousands before the
                        >casino realized their error...
                        My statement is more based on economics and psychology than
                        mathematics. If there's enough to gain, people will go to great
                        lengths to break your scheme, including stealing a machine (or
                        BUYING one) and taking it apart, bribing employees or ex-employees
                        to get source code and procedures, dedicating huge amounts of donated
                        CPU time under the guise of searching for aliens or a cure for
                        cancer, etc.

                        A really clever crack will not take so much in winnings that the
                        casino realizes it immediately, but will take less but over a longer
                        period of time.

                        Comment

                        • Malcolm McLean

                          #13
                          Re: How to generate random numbers in C


                          "Ben Bacarisse" <ben.usenet@bsb .me.ukwrote in message
                          news:87tzi7f28j .fsf@bsb.me.uk. ..
                          "Malcolm McLean" <regniztar@btin ternet.comwrite s:
                          >
                          >"pereges" <Broli00@gmail. comwrote in message news:
                          >>>I need to generate two uniform random numbers between 0 and 1 in C ?
                          >>How to do it ?
                          >>>
                          >>I looked into rand function where you need to #define RAND_MAX as 1
                          >>but will this rand function give me uniformly distributed and unique
                          >>numbers ?
                          >>>
                          >No, defining RAND_MAX as something else won't help. All it will do is
                          >make the identifier useless in the rest of your program, without
                          >touching the random number generator. Strictly it is UB in case
                          >RAND_MAX appears in some standard library macro or other.
                          >>
                          >This is the generally accpeted way to do it
                          >#define uniform() (rand() / (RAND_MAX + 1.0))
                          >#define rnd(x) ( (x) * uniform() )
                          >>
                          >we add 1.0 to make rand() never return exactly unity, so rnd() is
                          >always in the range 0 to x-1.
                          >
                          rnd(m) can be much closer to m than m-1. Did you mean:
                          >
                          #define rnd(x) ((int)((x) * uniform()))
                          >
                          perhaps? The OP wanted numbers between 0 and 1 so your uniform() is
                          sufficient if they mean doubles in [0,1).
                          >
                          That would be fine if int was 64 bits :-(

                          --
                          Free games and programming goodies.


                          Comment

                          • Richard Tobin

                            #14
                            Re: How to generate random numbers in C

                            In article <IA4Mj.177260$c Q1.25121@bgtnsc 04-news.ops.worldn et.att.net>,
                            Bill Reid <hormelfree@hap pyhealthy.netwr ote:
                            >In a fair game, the player with the biggest house money volume wins.
                            >Oh, a "fair game"...who the hell offers a "fair game"? In any event,
                            >it's irrelevant, because the actual most important factor (to the extent
                            >that we indulge in the pointless semantics of pronouncing a "most
                            >important factor") is the "expectatio n" of the game.
                            Actually, you can reliably win against poor odds if you have unlimited
                            resources and your opponent is required to accept your bets. Decide
                            how much you want to win. Bet enough to make that if you win. If you
                            do, quit. If you don't, bet enough to win back your losses plus your
                            desired win. If you can continue making bets in this manner, you will
                            eventually win, no matter how poor the odds.

                            In practice, you can't do this, because your resources are limited
                            compared to the Casino's. If they weren't, they would eventually
                            refuse your bet.

                            -- Richard
                            --
                            :wq

                            Comment

                            • Bill Reid

                              #15
                              Re: How to generate random numbers in C


                              Gordon Burditt <gordonb.l11qa@ burditt.orgwrot e in message
                              news:T7ydnSMQJK BSnJzVnZ2dnUVZ_ sytnZ2d@interne tamerica...
                              If you try to offer casino gambling games (e.g. craps, blackjack,
                              roulette, etc.) for real money using pseudo-random numbers, you're
                              going to lose.
                              There is no mathematical basis for this general statement, however,
                              there have been cases where people caught on to the sequence coming
                              from a poorly- or non-reseeded pseudo-random number generator
                              in a casino game and won hundreds of $thousands before the
                              casino realized their error...
                              >
                              My statement is more based on economics and psychology than
                              mathematics. If there's enough to gain, people will go to great
                              lengths to break your scheme,
                              There's a limit to greed; just because somebody offers $1trillion
                              to run a mile in one second doesn't mean anybody is ever going
                              to be able to do it, no matter how motivated they are and how
                              hard they try.
                              including stealing a machine (or
                              BUYING one) and taking it apart, bribing employees or ex-employees
                              to get source code and procedures, dedicating huge amounts of donated
                              CPU time under the guise of searching for aliens or a cure for
                              cancer, etc.
                              Sure, this all happens now, and has always happened. Back
                              when I used to consult for the electronic slot machine and lottery
                              equipment makers, a popular method of getting money from the
                              machines was to zap them with about a zillion volts, hopefully
                              sometimes causing the CPU to fritz out and activate the hopper
                              dump solenoid and dump the coins in the hopper into the "loud bowl".
                              Then they'd scoop up as many as they could and try to hit the
                              doors before security locked them (they were in most cases
                              already detected and being tracked by security cameras
                              the moment the coins dropped).

                              A slightly more sophisticated method involved an operation
                              using a small drill and a procedure not unlike othroscopic
                              surgery to trigger a hopper dump; in any event, they still
                              couldn't fake the internal sequence of microprocessor events
                              that had to occur and were always recorded that were evidence
                              of a genuine jackpot, along with those omnipresent security
                              cameras...

                              Guys who REALLY knew the machines could even have
                              a whole set of fake EEPROMs ready to install in seconds
                              after they jimmied open the door; but seriously, wouldn't
                              it just be easier to get a friggin' job?
                              A really clever crack will not take so much in winnings that the
                              casino realizes it immediately, but will take less but over a longer
                              period of time.
                              Oh, they'll figure it out eventually, but the problem will still
                              be to predict a series of pseudo-random numbers seeded from
                              some split-second event at pseudo-random times...this would
                              be tough enough under the best of circumstances, and in
                              a casino environment, purt near impossible, even WITH
                              "inside information"...

                              ---
                              William Ernest Reid



                              Comment

                              Working...