1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
# -*- mode: perl; -*-
use strict;
use warnings;
use Test::More tests => 4112;
use Scalar::Util qw< refaddr >;
use Math::BigInt;
# ceil(log(x) / log(2))
sub clog2 {
my $x = shift;
my $y = int(log($x) / log(2));
my $trial = 2 ** $y;
return $y if $trial == $x;
while ($trial > $x) {
$y--;
$trial = 2 ** $y;
}
while ($trial < $x) {
$y++;
$trial = 2 ** $y;
}
return $y;
}
my @cases =
(
[ "NaN", "NaN" ],
[ "-1", "NaN" ],
[ "0", "-inf" ],
);
for (my $x = 1 ; $x <= 1025 ; $x++) {
my $y = clog2($x);
push @cases, [ $x, $y ];
}
note("\nbclog2() as a class method");
for my $case (@cases) {
my ($test, $y, @y);
my ($in0, $out0) = @$case;
# Scalar context.
$test = qq|\$y = Math::BigInt -> bclog2("$in0");|;
note "\n", $test, "\n\n";
eval $test;
die $@ if $@;
subtest $test => sub {
plan tests => 2;
is(ref($y), 'Math::BigInt', '$y is a Math::BigInt');
is($y, $out0, 'value of $y');
};
# List context.
$test = qq|\@y = Math::BigInt -> bclog2("$in0");|;
note "\n", $test, "\n\n";
eval $test;
die $@ if $@;
subtest $test => sub {
plan tests => 3;
is(scalar(@y), 1, 'number of output arguments');
is(ref($y[0]), 'Math::BigInt', '$y[0] is a Math::BigInt');
is($y[0], $out0, 'value of $y[0]');
};
}
note("\nbclog2() as an instance method");
for my $case (@cases) {
my ($test, $x, $y, @y);
my ($in0, $out0) = @$case;
# Scalar context.
$test = qq|\$x = Math::BigInt -> new("$in0"); |
. qq|\$y = \$x -> bclog2();|;
note "\n", $test, "\n\n";
eval $test;
die $@ if $@;
subtest $test => sub {
plan tests => 2;
is(ref($y), 'Math::BigInt', '$y is a Math::BigInt');
is($y, $out0, 'value of $y');
};
# List context.
$test = qq|\@y = Math::BigInt -> bclog2("$in0");|;
note "\n", $test, "\n\n";
eval $test;
die $@ if $@;
subtest $test => sub {
plan tests => 3;
is(scalar(@y), 1, 'number of output arguments');
is(ref($y[0]), 'Math::BigInt', '$y[0] is a Math::BigInt');
is($y[0], $out0, 'value of $y[0]');
};
}
|