Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Writing a quasi-random number generator

by gryng (Hermit)
on Feb 19, 2001 at 19:15 UTC ( #59383=note: print w/replies, xml ) Need Help??


in reply to Re: Srand versus rand
in thread Pi calculator

Welp I can't remember off the top of my head how to do anything but Hamilton sequences. (And I'm fuzzy on one point that I'll mention below).

Hamilton sequences aren't very random looking for quasi-random numbers, but they are better than nothing :) . You choose a base b and a number n. You then write n in base b, reverse it's digits and add a decimal point in front. Convert the number back into whatever base you want to view it in, and you are done.

I gave an example with b = 2 and n going from 0 to 7 before (here). And here is where I'm fuzzy. I believe the best way to use Hamilton sequences is to not keep b constant and vary n.

Rather you should vary both n and b. I beleive you increment n sequencially, but increment b to the nth prime number. This seems right, but it could also be that you make b the next larger prime than n.

If you notice, if you keep b constant you fill in your area in a regular grid-like patern, with b dictating the initial fineness (but any b will give you an infinite sequence). This is why I'm fairly certain you should probably use one of the two techniques above to vary b, I just can't remember which one at the moment :) .

Here is a snippet (which hopefully works) that should generate the nth number for a base b in a Hamilton sequence. There will probably be faster, more robust, and/or shorter approaches (perl golf is encouraged :) ) :

sub hamilton { my ($n, $b) = @_; my ($a, $x) = (0, $b); while ($n) { $a += ($n % $b)/$x; $x = $x * $b; $n = int ($n / $b); } return $a; }

Back to work. Good luck.

Ciao,
Gryn

p.s. Note that it would be more accurate to calculate $a by reversing this loop (that is ($n % $b)/$x gets smaller as the loop progresses, and it would be better to add the smaller values of this term first, then proceed towards larger ones). This is a floating-point rounding issue only.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://59383]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2021-06-17 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (83 votes). Check out past polls.

    Notices?