File Coverage

blib/lib/sanity/BaseCalc.pm
Criterion Covered Total %
statement 40 112 35.7
branch 5 64 7.8
condition 2 28 7.1
subroutine 6 10 60.0
pod 0 4 0.0
total 53 218 24.3


line stmt bran cond sub pod time code
1             package # hide from PAUSE
2             sanity::BaseCalc;
3              
4             our $VERSION = '1.02'; # VERSION
5             # ABSTRACT: DO NOT USE!
6              
7 1     1   7 use strict;
  1         3  
  1         48  
8 1     1   7 use Carp;
  1         13  
  1         119  
9 1     1   7 use Math::BigInt 1.78; # 1.78 = round_mode => common
  1         37  
  1         10  
10 1     1   2782 use Math::BigFloat;
  1         27190  
  1         7  
11              
12             # configure some basic big number stuff
13             Math::BigInt ->config({
14             upgrade => 'Math::BigFloat',
15             round_mode => 'common',
16             trap_nan => 1,
17             trap_inf => 1,
18             });
19             Math::BigFloat->config({
20             round_mode => 'common',
21             trap_nan => 1,
22             trap_inf => 1,
23             });
24              
25             sub new {
26 2     2 0 15 my ($pack, %opts) = @_;
27 2         9 my $self = bless {}, $pack;
28 2   50     34 $self->{neg_char} = $opts{neg_char} || '-';
29 2   50     16 $self->{radix_char} = $opts{radix_char} || '.';
30 2 50       11 $opts{digits} = $_[1] if (@_ == 2);
31 2         10 $self->digits($opts{digits});
32 2         16 return $self;
33             }
34              
35             sub digits {
36 2     2 0 5 my $self = shift;
37 2 50       9 return @{$self->{digits}} unless (@_);
  0         0  
38              
39             # Set the value
40 2 50       11 if (ref $_[0] eq 'ARRAY') {
41 2         3 $self->{digits} = [ @{ shift() } ];
  2         10018  
42 2         11 delete $self->{digitset_name};
43             } else {
44 0         0 my $name = shift;
45 0         0 my %digitsets = $self->_digitsets;
46 0 0       0 croak "Unrecognized digit set '$name'" unless exists $digitsets{$name};
47 0         0 $self->{digits} = $digitsets{$name};
48 0         0 $self->{digitset_name} = $name;
49             }
50 2 50       8 $self->{neg_char} = '' if (grep { $_ eq $self->{neg_char} } @{$self->{digits}});
  48990         76351  
  2         262  
51 2 50       6 $self->{radix_char} = '' if (grep { $_ eq $self->{radix_char} } @{$self->{digits}});
  48990         96516  
  2         217  
52 2         5 $self->{digit_strength} = log(scalar @{$self->{digits}}) / log(10);
  2         19  
53              
54             # Build the translation table back to numbers
55 2         7 delete $self->{trans};
56 2         6 @{$self->{trans}}{@{$self->{digits}}} = 0..$#{$self->{digits}};
  2         74349  
  2         944  
  2         3667  
57              
58 2         2712 return @{$self->{digits}};
  2         12  
59             }
60              
61              
62             sub _digitsets {
63             return (
64 0     0     'bin' => [0,1],
65             'hex' => [0..9,'a'..'f'],
66             'HEX' => [0..9,'A'..'F'],
67             'oct' => [0..7],
68             '64' => ['A'..'Z','a'..'z',0..9,'+','/'],
69             '62' => [0..9,'a'..'z','A'..'Z'],
70             );
71             }
72              
73             sub from_base {
74 0     0 0   my ($self, $str) = @_;
75 0           my ($nc, $fc) = @$self{qw(neg_char radix_char)};
76 0 0 0       return $self->_from_accurate_return( Math::BigFloat->new( $self->from_base($str) )->bneg() )
77             if $nc && $str =~ s/^\Q$nc\E//; # Handle negative numbers
78              
79             # number clean up + decimal checks
80 0           my $base = @{$self->{digits}};
  0            
81 0           my $zero = $self->{digits}[0];
82 0   0       my $is_dec = ($fc && $str =~ /\Q$fc\E/);
83 0           $str =~ s/^\Q$zero\E+//;
84 0 0         $str =~ s/\Q$zero\E+$// if ($is_dec);
85              
86             # num of digits + big number support
87 0           my $poten_digits = int(length($str) * $self->{digit_strength}) + 16;
88 0           Math::BigFloat->accuracy($poten_digits + 16);
89 0           my $result = Math::BigFloat->new(0);
90 0 0         $result = $result->as_int() unless $is_dec;
91              
92             # short-circuits
93 0 0 0       unless ($is_dec || !$self->{digitset_name}) {
94 0 0         $result = $result->from_hex(lc "0x$str") if ($self->{digitset_name} =~ /^hex$/i);
95 0 0         $result = $result->from_bin( "0b$str") if ($self->{digitset_name} eq 'bin');
96 0 0         $result = $result->from_oct(lc "0$str") if ($self->{digitset_name} eq 'oct');
97             }
98              
99 0 0         if ($result == 0) {
100             # num of digits (power)
101 0           my $i = 0;
102 0           $i = length($str)- 1;
103             # decimal digits (yes, this removes the radix point, but $i captures the "digit location" information.)
104 0 0 0       $i = length($1) - 1 if ($fc && $str =~ s/^(.*)\Q$fc\E(.*)$/$1$2/);
105              
106 0           while ( $str =~ s/^(.)// ) {
107 0           my $v = $self->{trans}{$1};
108 0 0         croak "Invalid character $1 in string!" unless defined $v;
109              
110 0           my $exp = Math::BigInt->new($base);
111 0           $result = $exp->bpow($i)->bmul($v)->badd($result);
112 0           $i--; # may go into the negative for non-ints
113             }
114             }
115              
116 0           return $self->_from_accurate_return($result);
117             }
118              
119             sub _from_accurate_return {
120 0     0     my ($self, $result) = @_;
121              
122             # never lose the accuracy
123 0           my $rscalar = $result->numify();
124 0           my $rstring = $result->bstr();
125 0 0         $rstring =~ s/0+$// if ($rstring =~ /\./);
126 0           $rstring =~ s/\.$//; # float to whole number
127             # (the user can choose to put the string in a Math object if s/he so wishes)
128 0 0         return $rstring eq ($rscalar + 0 . '') ? $result->numify() : $rstring;
129             }
130              
131             sub to_base {
132 0     0 0   my ($self, $num) = @_;
133              
134             # decimal checks
135 0           my $base = scalar @{$self->{digits}};
  0            
136 0 0         my $is_dec = ($num =~ /\./) ? 1 : 0;
137 0 0         $is_dec = 0 unless $self->{radix_char};
138 0           my $zero = $self->{digits}[0];
139              
140             # num of digits + big number support
141 0           my $poten_digits = length($num);
142 0           Math::BigFloat->accuracy($poten_digits + 16);
143 0           $num = Math::BigFloat->new($num);
144 0 0 0       $num = $num->as_int() unless $is_dec && $self->{radix_char};
145              
146             # (hold off on this check until after the big number support)
147 0 0         return $self->{neg_char}.$self->to_base( $num->bneg ) if $num < 0; # Handle negative numbers
148              
149             # short-circuits
150 0 0         return $zero if ($num == 0); # this confuses log, so let's just get rid of this quick
151 0 0 0       unless ($is_dec || !$self->{digitset_name}) {
152 0 0         return substr(lc $num->as_hex(), 2) if ($self->{digitset_name} eq 'hex');
153 0 0         return substr(uc $num->as_hex(), 2) if ($self->{digitset_name} eq 'HEX');
154 0 0         return substr( $num->as_bin(), 2) if ($self->{digitset_name} eq 'bin');
155 0 0         return substr( $num->as_oct(), 1) if ($self->{digitset_name} eq 'oct');
156             }
157              
158             # get the largest power of Z (the highest digit)
159 0           my $i = $num->copy()->blog(
160             $base,
161             int($num->length() / 9) + 2 # (an accuracy that is a little over the potential # of integer digits within log)
162             )->bfloor()->numify();
163              
164 0           my $result = '';
165             # BigFloat's accuracy should counter this, but the $i check is
166             # to make sure we don't get into an irrational/cyclic number loop
167 0   0       while (($num != 0 || $i >= 0) && $i > -1024) {
      0        
168 0           my $exp = Math::BigFloat->new($base);
169 0 0         $exp = $i < 0 ? $exp->bpow($i) : $exp->as_int->bpow($i);
170 0           my $v = $num->copy()->bdiv($exp)->bfloor();
171 0           $num -= $v * $exp; # this method is safer for fractionals
172              
173 0 0         $result .= $self->{radix_char} if ($i == -1); # decimal point
174 0           $result .= $self->{digits}[$v];
175              
176 0           $i--; # may go into the negative for non-ints
177             }
178              
179             # Final cleanup
180 0 0         return $zero unless length $result;
181              
182 0           $result =~ s/^\Q$zero\E+//;
183 0 0         $result =~ s/\Q$zero\E+$// if ($is_dec);
184              
185 0           return $result;
186             }
187              
188             1;
189              
190             __END__
191              
192             =pod
193              
194             =encoding utf-8
195              
196             =head1 NAME
197              
198             sanity::BaseCalc - DO NOT USE!
199              
200             =head1 DESCRIPTION
201              
202             This module is only temporary until Math::BaseCalc is fixed
203             (L<RT #77198|https://rt.cpan.org/Ticket/Display.html?id=77198> and
204             L<Pull Request #2|https://github.com/kenahoo/perl-math-basecalc/pull/2>).
205             Do NOT use for anything else, as it will go away soon.
206              
207             =head1 SEE ALSO
208              
209             L<Math::BaseCalc>
210              
211             =head1 AVAILABILITY
212              
213             The project homepage is L<https://github.com/SineSwiper/sanity/wiki>.
214              
215             The latest version of this module is available from the Comprehensive Perl
216             Archive Network (CPAN). Visit L<http://www.perl.com/CPAN/> to find a CPAN
217             site near you, or see L<https://metacpan.org/module/sanity/>.
218              
219             =head1 AUTHOR
220              
221             Brendan Byrd <bbyrd@cpan.org>
222              
223             =head1 COPYRIGHT AND LICENSE
224              
225             This software is Copyright (c) 2013 by Brendan Byrd.
226              
227             This is free software, licensed under:
228              
229             The Artistic License 2.0 (GPL Compatible)
230              
231             =cut