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