in reply to Re: Srand versus rand
in thread Pi calculator
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.
|
|---|