Math.random()

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dr John Stockton

    #16
    Re: Math.random()

    JRS: In article <lln0ryj1.fsf@h otpop.com>, seen in
    news:comp.lang. javascript, Lasse Reichstein Nielsen <lrn@hotpop.com >
    posted at Wed, 18 Feb 2004 20:13:54 :-[color=blue]
    >Dr John Stockton <spam@merlyn.de mon.co.uk> writes:
    >[color=green]
    >> "My" method was taken from a reliable-seeming source, and most people
    >> seem willing to believe that it is best.[/color]
    >
    >Knuth's "The Art of Computer Programming" is not just reliable-seeming.
    >It is authoritative, going on definitive. :)[/color]

    But I did not get the method directly from Knuth; I only have it on
    hearsay that it's in Knuth, and the version I presented has been
    translated at least twice.

    --
    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
    <URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
    <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

    Comment

    • John M. Gamble

      #17
      Re: Math.random()

      In article <lln1qqk4.fsf@h otpop.com>,
      Lasse Reichstein Nielsen <lrn@hotpop.com > wrote:[color=blue]
      >jgamble@ripco. com (John M. Gamble) writes:
      >[color=green]
      >> In article <cHMLdJGqOfMAFw pb@merlyn.demon .co.uk>,
      >> Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:[/color]
      >[color=green][color=darkred]
      >>>By reading the FAQ and following its "shuffling" reference, you could
      >>>have found
      >>>
      >>> function Shuffle(Q) { var R, T, J
      >>> for (J=Q.length-1 ; J>0 ; J--)
      >>> { R=Random(J+1) ; T=Q[J] ; Q[J]=Q[R] ; Q[R]=T }
      >>> return Q }
      >>>
      >>>which is AFAICS the best possible Shuffle.[/color]
      >>
      >> This is actually well-known to be a bad shuffle algorithm.[/color]
      >...[color=green]
      >> The major flaw with this algorithm is that not all permutations are
      >> equally possible. This may not be the worst problem with a
      >> card-shuffling program, but i would be annoyed with it.[/color]
      >
      >I think you are misreading the algorithm. In particular, notice that
      >the call to Random uses the loop iterator as argument. It does perform[/color]

      Yes. It's still possible that i'm misreading the algorithm, of course,
      but i was aware of that.

      In a posting to sci.stat.math, sci.math and sci.crypt, on Octorber 7
      1999, subject: "Re: Perfect Shuffle Algorithm?" (I've changed the '>'
      characters to '-' to avoid confusion with the current mesage).

      -- The classic card-shuffling algorithm that I've seen and used does not
      -- replicate the human technique at all, but it produces a throughly
      -- scrambled deck instantly. In Pascal:

      -- for n := 52 downto 2 do SwapCards(n, Random(1,n));

      -- where "SwapCards" exchanges the position of two specified cards, and
      -- "Random(1,n )" produces a random number in the inclusive range [1..n].

      -I don't know your definition(s) of 'thoroughly' and 'instantly', but you
      -might find the comments in volume 2 of Knuth, starting with the
      -paragraph at the bottom of page 145 of the 3rd edition, of interest.
      -Partial quote "...cannot possibly generate more than..." Even with just
      -13 cards, the common random number generators based on 2^32 values can
      -not generate all shuffles.

      Herman Rubin then pointed out that you can if your random number
      source is good, but i will wager that Random does not meet sci.crypt's
      general criteria for 'good'.

      --
      -john

      February 28 1997: Last day libraries could order catalogue cards
      from the Library of Congress.

      Comment

      • John M. Gamble

        #18
        Re: Math.random()

        In article <L$6Oz8GzU3MAFw px@merlyn.demon .co.uk>,
        Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:[color=blue]
        >JRS: In article <c0ttmb$c62$1@e 250.ripco.com>, seen in
        >news:comp.lang .javascript, John M. Gamble <jgamble@ripco. com> posted at
        >Tue, 17 Feb 2004 20:31:07 :-[color=green][color=darkred]
        >>>By reading the FAQ and following its "shuffling" reference, you could
        >>>have found
        >>>
        >>> function Shuffle(Q) { var R, T, J
        >>> for (J=Q.length-1 ; J>0 ; J--)
        >>> { R=Random(J+1) ; T=Q[J] ; Q[J]=Q[R] ; Q[R]=T }
        >>> return Q }
        >>>
        >>>which is AFAICS the best possible Shuffle.[/color]
        >>
        >>This is actually well-known to be a bad shuffle algorithm.[/color]
        >
        >I don't believe you.
        >[/color]

        Uh, okay. Is that "I think you are a liar," or "I think you are
        mistaken?"
        [color=blue]
        >[color=green]
        >> The
        >>question comes up occasionally in sci.crypt, and also was discussed
        >>in detail in the comp.lang.perl. moderated newsgroup. I think that
        >>the perl FAQ was corrected with a much better shuffle as a result
        >>(look for the key word 'permute').[/color]
        >
        >I, like many others here, am a dial-up off-line user; so, where known,
        >"Please Give URL". The algorithm in the sci.crypto FAQ seems to be
        >equivalent to the above, encoded in C.[/color]

        Hmm. I'm a dial-upper myself. I'm not surprised that sci.crypt FAQ
        is not modified, since someone would actually have to take the time
        to bother. I did mention the perl FAQ (hmm. Assuming that whoever
        actually did bother - he said so, but i've not actually checked).
        [color=blue]
        >
        >[color=green]
        >>The major flaw with this algorithm is that not all permutations are
        >>equally possible.[/color]
        >
        >I certainly don't believe that.[/color]

        "Thus, for example, if m = 2**32, certain permutations of 13 elements
        will never occur, since 13! is approximately 1.45x2**32"
        Knuth TAoCP, p. 146, vol. 2 third edition.
        [color=blue]
        >[color=green]
        >> This may not be the worst problem with a
        >>card-shuffling program, but i would be annoyed with it.[/color]
        >
        >Agreed that it would be a major flaw.
        >[color=green]
        >>The algorithm (or one of them) that should be looked at is the
        >>Fischer-Krause algorithm.[/color]
        >
        >PGU.[/color]

        Which stand for?

        --
        -john

        February 28 1997: Last day libraries could order catalogue cards
        from the Library of Congress.

        Comment

        • Lasse Reichstein Nielsen

          #19
          Re: Math.random()

          jgamble@ripco.c om (John M. Gamble) writes:
          [color=blue]
          > Yes. It's still possible that i'm misreading the algorithm, of course,
          > but i was aware of that.
          >
          > In a posting to sci.stat.math, sci.math and sci.crypt, on Octorber 7
          > 1999, subject: "Re: Perfect Shuffle Algorithm?" (I've changed the '>'
          > characters to '-' to avoid confusion with the current mesage).
          >
          > -- The classic card-shuffling algorithm that I've seen and used does not
          > -- replicate the human technique at all, but it produces a throughly
          > -- scrambled deck instantly. In Pascal:
          >
          > -- for n := 52 downto 2 do SwapCards(n, Random(1,n));[/color]

          You didn't misread then, that is the algorithm :)
          [color=blue]
          > -Even with just
          > -13 cards, the common random number generators based on 2^32 values can
          > -not generate all shuffles.[/color]

          If the period of the pseudo-random number generator is 2^32, then indeed,
          it can at most generate 2^32 different shuffles, which is less than the
          13! needed. I never thought of that restriction. :)

          In fact, that restriction holds for any shuffling algorithm using a
          PRNG with a period of 2^32.

          If you can actually generate randomness enough to get 52! different
          outcomes, this algorithm uses exactly that much, making each shuffle
          equally likely.
          [color=blue]
          > Herman Rubin then pointed out that you can if your random number
          > source is good, but i will wager that Random does not meet sci.crypt's
          > general criteria for 'good'.[/color]

          Yes, there is a big difference between a statistically good PRNG, and
          a cryptographical ly strong one (or so I have been told :).

          /L
          --
          Lasse Reichstein Nielsen - lrn@hotpop.com
          DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
          'Faith without judgement merely degrades the spirit divine.'

          Comment

          • Brian Genisio

            #20
            Re: Math.random()

            Lasse Reichstein Nielsen wrote:[color=blue]
            > jgamble@ripco.c om (John M. Gamble) writes:
            >
            >[color=green]
            >>Yes. It's still possible that i'm misreading the algorithm, of course,
            >>but i was aware of that.
            >>
            >>In a posting to sci.stat.math, sci.math and sci.crypt, on Octorber 7
            >>1999, subject: "Re: Perfect Shuffle Algorithm?" (I've changed the '>'
            >>characters to '-' to avoid confusion with the current mesage).
            >>
            >>-- The classic card-shuffling algorithm that I've seen and used does not
            >>-- replicate the human technique at all, but it produces a throughly
            >>-- scrambled deck instantly. In Pascal:
            >>
            >>-- for n := 52 downto 2 do SwapCards(n, Random(1,n));[/color]
            >
            >
            > You didn't misread then, that is the algorithm :)
            >
            >[color=green]
            >>-Even with just
            >>-13 cards, the common random number generators based on 2^32 values can
            >>-not generate all shuffles.[/color]
            >
            >
            > If the period of the pseudo-random number generator is 2^32, then indeed,
            > it can at most generate 2^32 different shuffles, which is less than the
            > 13! needed. I never thought of that restriction. :)
            >
            > In fact, that restriction holds for any shuffling algorithm using a
            > PRNG with a period of 2^32.
            >
            > If you can actually generate randomness enough to get 52! different
            > outcomes, this algorithm uses exactly that much, making each shuffle
            > equally likely.
            >
            >[color=green]
            >>Herman Rubin then pointed out that you can if your random number
            >>source is good, but i will wager that Random does not meet sci.crypt's
            >>general criteria for 'good'.[/color]
            >
            >
            > Yes, there is a big difference between a statistically good PRNG, and
            > a cryptographical ly strong one (or so I have been told :).
            >
            > /L[/color]

            To add a left turn into the conversation, a human, using a typical
            shuffle, splitting a deck in two, and joining them, cannot create all
            52! outcomes either. It is really just a combination of the two piles,
            based on a given deck state. You can shuffle more than once, and have
            more combos, but still, not all combos are equally likely.

            With that, if you want to simulate a (typical) human shuffle, you really
            only need to have random numbers between 1 and 10, where 1,2,3 are more
            likely than 10 (if you are en experienced shuffler). Then, you take a
            given deck, split it in half (with a random deviance), and take random
            ammounts from each side, one side, and then annother.

            Then, do it one or two more times. This, to me seems more likely to be
            a good shuffle algorithm for a card game. Oh yeah... dont forget to
            split the deck :)

            I did something like this, in a blackjack simulator... I wanted to test
            betting techniques over a long period of time. I actually shuffled a
            deck of cards about 20 times, and tallied up the probabilty of the
            different card chunks that added together to a single deck. I found
            that numbers such as 2 and 3 were much more common than 1 and 4, where 5
            and 6 were practically unheard of. I used these stats to generate my
            shuffle.

            Ultimately, I scrapped the program, because it didn't deal with the many
            factors that cannot be programmed, such as human emotion around the
            table, and bad playing decisions on other player's parts. This threw a
            mix into the final hand that made the my subtle shuffling algorithm
            practically useless :)

            Anyways, that is just a sidenote.

            Brian

            Comment

            • John M. Gamble

              #21
              Re: Math.random()

              In article <4035fc44$1@10. 10.0.241>,
              Brian Genisio <BrianGenisio@y ahoo.com> wrote:[color=blue]
              >Lasse Reichstein Nielsen wrote:[color=green]
              >> jgamble@ripco.c om (John M. Gamble) writes:
              >>
              >>[color=darkred]
              >>>Yes. It's still possible that i'm misreading the algorithm, of course,
              >>>but i was aware of that.
              >>>
              >>>In a posting to sci.stat.math, sci.math and sci.crypt, on Octorber 7
              >>>1999, subject: "Re: Perfect Shuffle Algorithm?" (I've changed the '>'
              >>>characters to '-' to avoid confusion with the current mesage).
              >>>
              >>>-- The classic card-shuffling algorithm that I've seen and used does not
              >>>-- replicate the human technique at all, but it produces a throughly
              >>>-- scrambled deck instantly. In Pascal:
              >>>
              >>>-- for n := 52 downto 2 do SwapCards(n, Random(1,n));[/color]
              >>
              >>
              >> You didn't misread then, that is the algorithm :)
              >>
              >>[color=darkred]
              >>>-Even with just
              >>>-13 cards, the common random number generators based on 2^32 values can
              >>>-not generate all shuffles.[/color]
              >>
              >>
              >> If the period of the pseudo-random number generator is 2^32, then indeed,
              >> it can at most generate 2^32 different shuffles, which is less than the
              >> 13! needed. I never thought of that restriction. :)
              >>
              >> In fact, that restriction holds for any shuffling algorithm using a
              >> PRNG with a period of 2^32.
              >>
              >> If you can actually generate randomness enough to get 52! different
              >> outcomes, this algorithm uses exactly that much, making each shuffle
              >> equally likely.
              >>
              >>[color=darkred]
              >>>Herman Rubin then pointed out that you can if your random number
              >>>source is good, but i will wager that Random does not meet sci.crypt's
              >>>general criteria for 'good'.[/color]
              >>
              >>
              >> Yes, there is a big difference between a statistically good PRNG, and
              >> a cryptographical ly strong one (or so I have been told :).
              >>
              >> /L[/color]
              >
              >To add a left turn into the conversation, a human, using a typical
              >shuffle, splitting a deck in two, and joining them, cannot create all
              >52! outcomes either. It is really just a combination of the two piles,
              >based on a given deck state. You can shuffle more than once, and have
              >more combos, but still, not all combos are equally likely.
              >[/color]

              To add yet another left turn to this, the act of human-shuffling is
              not the only randomizer. Tossing in the cards after play, and
              scooping them up will have an effect too. Heck, the type of game
              will make a difference, since cards will be collected by players
              in a different order depending upon whether they are playing
              bridge or blackjack.
              [color=blue]
              >With that, if you want to simulate a (typical) human shuffle, you really
              >only need to have random numbers between 1 and 10, where 1,2,3 are more
              >likely than 10 (if you are en experienced shuffler). Then, you take a
              >given deck, split it in half (with a random deviance), and take random
              >ammounts from each side, one side, and then annother.
              >
              >Then, do it one or two more times. This, to me seems more likely to be
              >a good shuffle algorithm for a card game. Oh yeah... dont forget to
              >split the deck :)[/color]

              Heh. Of course there's always the "smear them around on the table"
              method - a friend of mine would do that. She swore up and down that
              she just couldn't do the classical shuffle.

              And then there's the other type of shuffle (or is it properly called
              a shuffle?), wherein one holds part of the deck in one hand, while
              sort-of tossing the remaining cards back in with the other. I know
              it has a name, but i can't remember it.
              [color=blue]
              >
              >I did something like this, in a blackjack simulator... I wanted to test
              >betting techniques over a long period of time. I actually shuffled a
              >deck of cards about 20 times, and tallied up the probabilty of the
              >different card chunks that added together to a single deck. I found
              >that numbers such as 2 and 3 were much more common than 1 and 4, where 5
              >and 6 were practically unheard of. I used these stats to generate my
              >shuffle.
              >
              >Ultimately, I scrapped the program, because it didn't deal with the many
              >factors that cannot be programmed, such as human emotion around the
              >table, and bad playing decisions on other player's parts. This threw a
              >mix into the final hand that made the my subtle shuffling algorithm
              >practically useless :)
              >
              >Anyways, that is just a sidenote.
              >[/color]

              Interesting though. Thanks.

              --
              -john

              February 28 1997: Last day libraries could order catalogue cards
              from the Library of Congress.

              Comment

              • John M. Gamble

                #22
                Re: Math.random()

                In article <smh6k7el.fsf@h otpop.com>,
                Lasse Reichstein Nielsen <lrn@hotpop.com > wrote:[color=blue]
                >jgamble@ripco. com (John M. Gamble) writes:
                >[color=green]
                >> Herman Rubin then pointed out that you can if your random number
                >> source is good, but i will wager that Random does not meet sci.crypt's
                >> general criteria for 'good'.[/color]
                >
                >Yes, there is a big difference between a statistically good PRNG, and
                >a cryptographical ly strong one (or so I have been told :).
                >[/color]

                Yes, although in this case i believe it doesn't make a difference.

                Hmm. I may be making an unwarranted assumption. I wrote my
                previous message under the belief that javascript's Random is just
                as statistically lousy as every other language's Random/rand/rnd
                built-in or library-supplied function[1]. (Outside the function's
                natural period, of course). Is that true? Has Random been tested
                with the diehard suite?

                [1] Excepting specially written packages which are not normally
                included by default. Perl has Math::TrulyRand om; Java has
                something like that too but i can't remember the name.

                --
                -john

                February 28 1997: Last day libraries could order catalogue cards
                from the Library of Congress.

                Comment

                • Dr John Stockton

                  #23
                  Re: Math.random()

                  JRS: In article <c139s9$5k1$2@e 250.ripco.com>, seen in
                  news:comp.lang. javascript, John M. Gamble <jgamble@ripco. com> posted at
                  Thu, 19 Feb 2004 21:29:45 :-[color=blue]
                  >In article <L$6Oz8GzU3MAFw px@merlyn.demon .co.uk>,
                  >Dr John Stockton <spam@merlyn.de mon.co.uk> wrote:[color=green]
                  >>JRS: In article <c0ttmb$c62$1@e 250.ripco.com>, seen in
                  >>news:comp.lan g.javascript, John M. Gamble <jgamble@ripco. com> posted at
                  >>Tue, 17 Feb 2004 20:31:07 :-[color=darkred]
                  >>>>By reading the FAQ and following its "shuffling" reference, you could
                  >>>>have found
                  >>>>
                  >>>> function Shuffle(Q) { var R, T, J
                  >>>> for (J=Q.length-1 ; J>0 ; J--)
                  >>>> { R=Random(J+1) ; T=Q[J] ; Q[J]=Q[R] ; Q[R]=T }
                  >>>> return Q }
                  >>>>
                  >>>>which is AFAICS the best possible Shuffle.[/color][/color][/color]
                  [color=blue][color=green]
                  >>I, like many others here, am a dial-up off-line user; so, where known,
                  >>"Please Give URL". The algorithm in the sci.crypto FAQ seems to be
                  >>equivalent to the above, encoded in C.[/color][/color]

                  [color=blue][color=green][color=darkred]
                  >>>The major flaw with this algorithm is that not all permutations are
                  >>>equally possible.[/color]
                  >>
                  >>I certainly don't believe that.[/color]
                  >
                  >"Thus, for example, if m = 2**32, certain permutations of 13 elements
                  >will never occur, since 13! is approximately 1.45x2**32"
                  > Knuth TAoCP, p. 146, vol. 2 third edition.[/color]

                  I was explicitly referring to the Shuffle algorithm; immediately above
                  what you quoted I had written "(assuming, that is, a perfect Random
                  function)." which you evidently failed to appreciate; ISTM evident that
                  it must apply to the paragraph below.

                  [color=blue][color=green][color=darkred]
                  >>>The algorithm (or one of them) that should be looked at is the
                  >>>Fischer-Krause algorithm.[/color]
                  >>
                  >>PGU.[/color]
                  >
                  >Which stand for?[/color]

                  The words "Please Give URL" appeared earlier in my previous article ...

                  --
                  © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                  Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                  Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                  Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                  Comment

                  • Dr John Stockton

                    #24
                    Re: Math.random()

                    JRS: In article <smh6k7el.fsf@h otpop.com>, seen in
                    news:comp.lang. javascript, Lasse Reichstein Nielsen <lrn@hotpop.com >
                    posted at Thu, 19 Feb 2004 23:53:54 :-
                    [color=blue]
                    >If the period of the pseudo-random number generator is 2^32, then indeed,
                    >it can at most generate 2^32 different shuffles, which is less than the
                    >13! needed. I never thought of that restriction. :)
                    >
                    >In fact, that restriction holds for any shuffling algorithm using a
                    >PRNG with a period of 2^32.[/color]

                    Agreed.

                    The situation may be worse than you think, although (since,
                    unfortunately, the seed is not visible in javascript and its method of
                    generation is not evident) it's not necessarily easy to be sure.

                    Consider a Web page that generates a pack cards in logical order and
                    then, exactly once, applies a perfect shuffle method algorithm which,
                    however, calls the built-in Math.random.

                    It is already established that a system you use has a 32-bit seed (AIUI,
                    probable as that seems, it is not established that it uses R[n+1] =
                    (A*R[n]+B) mod 2^32) ; and that mine apparently uses a larger seed, 53
                    bits or more.

                    ASIDE A good Shuffle of N cards calls Random N times, or N-1 times; if
                    that number has a factor M in common with the cycle length C of
                    the PRNG (with N=52 or 53, M=4 is likely), then the cycle length
                    of the random sequences used will be C/M. However, C/M shuffles
                    probably leave the deck in a new order. Better to shuffle than
                    to deal a new deck every time.
                    /ASIDE

                    Given the shuffle method and the PRNG method, the result of the single
                    shuffle is determined by the initial value of the seed.

                    Ideally, this will itself be random.

                    But there is, in most systems, no intrinsic source of genuine random.

                    I believe some form of the time is usually used, perhaps permuted.

                    The Pascal that I use takes this time from the DOS clock at $40:6C,
                    which ticks (@55ms) $1800B0 times per day and then repeats. Only
                    $1800B0 of the $100000000 initial seeds can be given, 1/2730 of the
                    ideal. My Delphi, D3, is equivalent. Delphi 7, at least, does better.
                    ( <URL:http://www.merlyn.demo n.co.uk/pas-rand.htm> )

                    Javascript clearly has access to time with a resolution of 55ms or 10ms
                    (in Windows; what might it have on non-PC systems?); at 55ms, 2730 days
                    will be needed to get all 32-bit seeds.

                    One cannot be sure, without evidence, when the seed is initialised -
                    when the browser is loaded, when the window is opened, when the page is
                    loaded, when Math.random is first called, ...

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                    Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
                    Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
                    Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

                    Comment

                    Working...