John W. Krahn wrote:
> Aruna Goke wrote:
>> I have worked on the code below and am able to generate the 15digit 
>> lenght required .
>>
>> However, what i wish to achieve is to make sure all the output comes out 
>> in 15 digits each. a sample of my output is as below.
>>
>> Can someone guide on how to make all come out in 15digits.
> 
> print sprintf( '%.30f', rand ) =~ /\.(\d{15})/;

This solution (as well as Gunnar's) relies on the available precision of the
rand function, which is determined when Perl is built. The number of bits can be
shown by executing

  perl -MConfig -e "print $Config{randbits}"

and on ActiveState Perl, at least, it is only 15 bits, corresponding to 4.5
decimal digits.

Expanding this limited amount of precision over 15 decimal digits will produce
very poor random numbers, and it is far better to concatenate the results from
five calls to rand(1000) unless the quality of randomness is of no consequence.

The program below shows ten numbers produced using both methods, and even in
this small sample the problem is clear.

HTH,

Rob


use strict;
use warnings;

print "Using single call to rand()\n";
foreach (1...10) {
  my $n = rand15a();
  print "$n\n";
}

print "\n\nUsing five calls to rand()\n";

foreach (1...10) {
  my $n = rand15b();
  print "$n\n";
}

sub rand15a {
  my ($r15) = sprintf( '%.30f', rand ) =~ /\.(\d{15})/;
  $r15;
}

sub rand15b {
  my $r15;
  $r15 .= sprintf "%03d", rand 1_000 for 1 .. 5;
  $r15;
}

**OUTPUT**

Using single call to rand()
583312988281250
378173828125000
031066894531250
559173583984375
217193603515625
908050537109375
164520263671875
936859130859375
908111572265625
888763427734375


Using five calls to rand()
485911983221141
991568078471086
657810917897561
740256349243263
935703599145794
523194437953137
491906142761110
386269935142967
489434048410568
299184714819156


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to