Perl: the Markov chain saw PerlMonks

### Re: Accuracy of Random Pi

by Fingo (Monk)
 on Feb 16, 2001 at 07:47 UTC ( #58781=note: print w/replies, xml ) Need Help??

in reply to Accuracy of Random Pi

```#!/usr/bin/perl
# This is a quick program to calculate pi using the Monte Carlo method
+.
# I recomend inputting  a value for \$cycles greater that 1000.
# I am working on a detailed explanation of how and why this works.
# I will add it as soon as I'm done.
use strict;
open(PI, ">>pi.dat") || die "pi.dat";
my (\$i, \$j, \$yespi, \$pi) = 1;
my \$cycles = 1;
srand;
while (\$j <= 100000) {
\$cycles = \$j;
while (\$i <= \$cycles) {
my (\$x, \$y, \$cdnt) = 1;
\$x = rand;
\$y = rand;
\$cdnt = \$x**2 + \$y**2;
if (\$cdnt <= 1) {
++\$yespi;
}
\$i=\$i + 10;
\$pi = (\$yespi / (\$cycles / 10)) * 4; # since I add 10 every time.
print PI "\$cycles \$pi\n";
}
\$j = \$j + 10;
}
close(PI) || die "pi.dat";
Here is the modified script I was talking about. If you look at pi.dat it starts getting inacurate at one point. I will try using one of the ways to genereate seeds that are slightly more random than plain srand. Note: you need to make a file pi.dat for the script to run.

Replies are listed 'Best First'.
Srand versus rand
by gryng (Hermit) on Feb 16, 2001 at 11:21 UTC
I'm not sure if setting srand would really help the situation. In order for the Monte Carlo method to be most effective the random numbers produced must be the most evenly spread out. In fact, you can be more accurate without random numbers and instead going through all four corners, then their mid-points, and their mid-points' mid-points, e.g. :
```.   .      . . .
->  . . .  ->  etc.
.   .      . . .

However, if you would like to use random numbers you need one of two types of random numbers. You either need true even-bias random numbers (pseudo-random can work but often don't :) ). Or you can use a particular kind of random numbers that are designed not to repeat and are garunteed to be spread evenly and more and more closely together (very similar to the systematic approach above).

Two examples are Hamilton and Sobol sequences. If you use them, you get a 1/N convergence, instead of a 1/N^2 (which you get for uniform numbers since there is nothing that keeps them from clumping up). I was going to give below "Numerical Recipe's in C"'s version of Antonov-Saleev's variant on Sobol's sequence. However it's simply too long. Also, I have to wake up for work tomorrow, and the first version I typed in (converting it to Perl from C) didn't work just right. Oh well.

Good luck, Hamilton sequences are much easier to do.

Ciao,
Gryn

Nope, letting perl set srand is good enough. And you are right about Monte Carlo needing a purer random base than a pseudo-random generator. Most Monte Carlo's use scads of randoms per cycle and you loop the psuedo random in 2**31 calls on most systems and 2**15 on some.

Look to CPAN and you will find some of what you need. First off, if you are going to write your own "random" sequence generator you my find PDL handy. If you want someone else to do the work on random numbers try Math::Random or Math::TrulyRandom but I would recommend you find an OS specific random source like Linux's /dev/random and /dev/urandom

```#!/usr/bin/perl -w
use strict;
#use Linux; ## I wish. =) (yeah yeah, \$^O, etc etc)

open UR, "</dev/urandom" or die "Oh man, your system sucks, \$!";

my \$pages= shift()+0 || 1;

die "Give me a number greater than 0 or nothing, bub.\n" unless \$pages
+>0;

while (\$pages-->0) {
my \$buf;
read UR, \$buf, 512 or die "Ouch that shouldn't happen, \$!";
for (0..31) {
print vec(\$buf,\$_*4,32), "\t",
vec(\$buf,\$_*4+1,32), "\t",
vec(\$buf,\$_*4+2,32), "\t",
vec(\$buf,\$_*4+3,32), "\n";
}
}

--
\$you = new YOU;
honk() if \$you->love(perl)

It shoulden't matter if there are repeats or not. As long as they do not apper in the same order, it woulden't really matter since I am looking to see if A^2 + B^2 is below 1. Actualy if I make 2 pairs of numbers one pair that A^2 + B^2 is less than 1, and another where it is not. Than I can generate the order in which they appear by some random factor (take a random number and each digit is used to see which of the 2 pairs I choose depending on if it's even or not). UPDATE: I now realize what I said was wrong randomly generating true or false will not generate Pi. Random numbers are sometimes very hard to visualize
A trick I have mentioned before and may again.

If you need a large supply of random looking data, one of the best approaches is to grab a large file produced out of dynamic data (/dev/mem is often a good bet, there are plenty of choices though), compress it, and then encrypt it with a good algorithm. Samples from the resulting file are for all intents and purposes, random.

In fact, this is a good source of random data. However, because it is a good source, it could easily be bad for Monte-Carlo searching. As I've been suggesting in other posts, Monte-Carlo searching benefits from uniform-distributed numbers.

But truely random numbers are not statistically garunteed to be uniformly distributed (no, the law of averages does not work that way :) ), and so they cause Monte-Carlo searching to converge more slowly (but do not keep it from converging).

This is why psuedo-random numbers can, theoretically, be better than truely-random numbers, because often they are crafted to be uniformly distributed -- statistically. However, it often occurs in practice that pseudo-random numbers are not perfectly statistically uniformly distributed (what a mouthful), and so can easily lead to a mis-convergance.

Enter Quasi-random numbers. These are uniformly-distributed and have a bias towards non-repetition. This means that you still get a garunteed convergence and you get it faster (since there would be no clumps in your set).

Ok, time to go.

Ciao,
Gryn

I did a search on CPAN for a quasi-random number generation module, but sadly could not find one. I will try the systematic dot approch that you mentioned, but this has interested me very much. Can you please tell me how I could go about writing a quasi-random number generator? Building a module will be good practice anyway, even if I can go without it ;)
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.

Create A New User
Node Status?
node history
Node Type: note [id://58781]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (4)
As of 2021-05-12 22:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
Perl 7 will be out ...

Results (134 votes). Check out past polls.

Notices?