This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate mainline
[perl5.git] / lib / Math / BigInt / t / mbi_rand.t
1 #!/usr/bin/perl -w
2
3 use Test;
4 use strict;
5
6 my $count;
7   
8 BEGIN
9   {
10   $| = 1;
11   unshift @INC, '../lib'; # for running manually
12   my $location = $0; $location =~ s/mbi_rand.t//;
13   unshift @INC, $location; # to locate the testing files
14   chdir 't' if -d 't';
15   $count = 128;
16   plan tests => $count*2;
17   }
18
19 use Math::BigInt;
20 my $c = 'Math::BigInt';
21
22 my $length = 128;
23
24 # If you get a failure here, please re-run the test with the printed seed
25 # value as input: perl t/mbi_rand.t seed
26
27 my $seed = ($#ARGV == 0) ? $ARGV[0] : int(rand(65537));
28 print "# seed: $seed\n"; srand($seed);
29
30 my ($A,$B,$As,$Bs,$ADB,$AMB,$la,$lb);
31 my $two = Math::BigInt->new(2);
32 for (my $i = 0; $i < $count; $i++)
33   {
34   # length of A and B
35   $la = int(rand($length)+1); $lb = int(rand($length)+1);
36   $As = ''; $Bs = '';
37   # we create the numbers from "patterns", e.g. get a random number and a
38   # random count and string them together. This means things like
39   # "100000999999999999911122222222" are much more likely. If we just strung
40   # together digits, we would end up with "1272398823211223" etc.
41   while (length($As) < $la) { $As .= int(rand(100)) x int(rand(16)); }
42   while (length($Bs) < $lb) { $Bs .= int(rand(100)) x int(rand(16)); }
43   $As =~ s/^0+//; $Bs =~ s/^0+//; 
44   $As = $As || '0'; $Bs = $Bs || '0';
45   # print "# As $As\n# Bs $Bs\n";
46   $A = $c->new($As); $B = $c->new($Bs);
47   # print "# A $A\n# B $B\n";
48   if ($A->is_zero() || $B->is_zero())
49     {
50     ok (1,1); ok (1,1); next;
51     }
52   # check that int(A/B)*B + A % B == A holds for all inputs
53   # $X = ($A/$B)*$B + 2 * ($A % $B) - ($A % $B);
54   ($ADB,$AMB) = $A->copy()->bdiv($B);
55   print "# ". join(' ',Math::BigInt::Calc->_base_len()),"\n"
56    unless ok ($ADB*$B+$two*$AMB-$AMB,$As);
57   # swap 'em and try this, too
58   # $X = ($B/$A)*$A + $B % $A;
59   ($ADB,$AMB) = $B->copy()->bdiv($A);
60   print "# ". join(' ',Math::BigInt::Calc->_base_len()),"\n"
61    unless ok ($ADB*$A+$two*$AMB-$AMB,$Bs);
62   }
63