Klaas has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I've got a problem with the precision of the random number generator.
I want if() to be true at a rate of 1/40.000, however, rand() is not precise enough and outputs 0 quite often (maybe a bit dept problem?). e.g.
if(rand(40.000)<1) is true ~ 100/40.000I tried rand(n)-1>n-1, or using the Math::Random module but this does not improve the randomness enough.
Example code:Thanks!use strict; use warnings; my $time = 120; my $D=10000; my $dt=1/$D; my $tt=0; my $rateon=1; my $count=0; while($time>$tt){ $tt=$tt+$dt; my $rand = rand($D); if(($rand)<=$rateon) { $count++; printf("%f > %f\n", $rateon, $rand) or die $!; } } print "$count total" or die $!;
Update: This hack works, although is not ideal:
use strict; use warnings; my $time = 120; my $D=10000; my $sqrtd=sqrt($D); my $dt=1/$D; my $tt=0; my $rateon=40; my $count=0; while($time>$tt){ $tt=$tt+$dt; my $rand = rand($sqrtd); my $rand2 = rand($sqrtd); if($rand<1 && $rand2<1 && rand($rateon)<1) { $count++; } } print "$count total " or die $!;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: rand() precision low, looking for a fast way to get high precision rand float?
by BrowserUk (Patriarch) on Oct 31, 2012 at 17:15 UTC | |
Re: rand() precision low, looking for a fast way to get high precision rand float?
by bart (Canon) on Oct 31, 2012 at 19:53 UTC | |
Re: rand() precision low, looking for a fast way to get high precision rand float?
by space_monk (Chaplain) on Oct 31, 2012 at 16:37 UTC |
Back to
Seekers of Perl Wisdom