← Index
NYTProf Performance Profile   « block view • line view • sub view »
For mentat.storage.mongo.pl
  Run on Tue Jun 24 09:58:41 2014
Reported on Tue Jun 24 09:59:18 2014

Filename/usr/share/perl/5.14/Math/BigInt.pm
StatementsExecuted 1005 statements in 35.8ms
Subroutines
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
9112.21ms24.7msMath::BigInt::::importMath::BigInt::import
1021362µs453µsMath::BigInt::::newMath::BigInt::new
111137µs1.08msMath::BigInt::::BEGIN@44Math::BigInt::BEGIN@44
366164µs64µsMath::BigInt::::CORE:matchMath::BigInt::CORE:match (opcode)
88152µs448µsMath::BigInt::::__ANON__[:2702]Math::BigInt::__ANON__[:2702]
11146µs46µsMath::BigInt::::TIESCALARMath::BigInt::TIESCALAR
11146µs92µsMath::BigInt::::BEGIN@193Math::BigInt::BEGIN@193
11144µs44µsMath::BigInt::::BEGIN@19Math::BigInt::BEGIN@19
11139µs46µsMath::BigInt::::round_modeMath::BigInt::round_mode
21136µs218µsMath::BigInt::::blsftMath::BigInt::blsft
11124µs50µsMath::BigInt::::BEGIN@2623Math::BigInt::BEGIN@2623
11121µs42µsMath::BigInt::::BEGIN@336Math::BigInt::BEGIN@336
11119µs45µsMath::BigInt::::BEGIN@3069Math::BigInt::BEGIN@3069
11118µs39µsMath::BigInt::::BEGIN@239Math::BigInt::BEGIN@239
21117µs17µsMath::BigInt::::roundMath::BigInt::round
11117µs46µsMath::BigInt::::BEGIN@943Math::BigInt::BEGIN@943
11117µs41µsMath::BigInt::::BEGIN@879Math::BigInt::BEGIN@879
11116µs39µsMath::BigInt::::BEGIN@656Math::BigInt::BEGIN@656
22116µs291µsMath::BigInt::::__ANON__[:121]Math::BigInt::__ANON__[:121]
11116µs23µsMath::BigInt::::BEGIN@30Math::BigInt::BEGIN@30
11116µs38µsMath::BigInt::::BEGIN@225Math::BigInt::BEGIN@225
11116µs39µsMath::BigInt::::BEGIN@447Math::BigInt::BEGIN@447
11116µs226µsMath::BigInt::::BEGIN@28Math::BigInt::BEGIN@28
11115µs37µsMath::BigInt::::BEGIN@377Math::BigInt::BEGIN@377
11115µs38µsMath::BigInt::::BEGIN@690Math::BigInt::BEGIN@690
11115µs36µsMath::BigInt::::BEGIN@278Math::BigInt::BEGIN@278
11115µs38µsMath::BigInt::::BEGIN@207Math::BigInt::BEGIN@207
11115µs38µsMath::BigInt::::BEGIN@548Math::BigInt::BEGIN@548
11114µs34µsMath::BigInt::::BEGIN@253Math::BigInt::BEGIN@253
11114µs34µsMath::BigInt::::BEGIN@470Math::BigInt::BEGIN@470
11113µs59µsMath::BigInt::::STOREMath::BigInt::STORE
21112µs19µsMath::BigInt::::is_zeroMath::BigInt::is_zero
9116µs6µsMath::BigInt::::CORE:substMath::BigInt::CORE:subst (opcode)
2111µs1µsMath::BigInt::::modifyMath::BigInt::modify (xsub)
0000s0sMath::BigInt::::FETCHMath::BigInt::FETCH
0000s0sMath::BigInt::::__ANON__[:100]Math::BigInt::__ANON__[:100]
0000s0sMath::BigInt::::__ANON__[:101]Math::BigInt::__ANON__[:101]
0000s0sMath::BigInt::::__ANON__[:106]Math::BigInt::__ANON__[:106]
0000s0sMath::BigInt::::__ANON__[:107]Math::BigInt::__ANON__[:107]
0000s0sMath::BigInt::::__ANON__[:108]Math::BigInt::__ANON__[:108]
0000s0sMath::BigInt::::__ANON__[:112]Math::BigInt::__ANON__[:112]
0000s0sMath::BigInt::::__ANON__[:115]Math::BigInt::__ANON__[:115]
0000s0sMath::BigInt::::__ANON__[:118]Math::BigInt::__ANON__[:118]
0000s0sMath::BigInt::::__ANON__[:124]Math::BigInt::__ANON__[:124]
0000s0sMath::BigInt::::__ANON__[:127]Math::BigInt::__ANON__[:127]
0000s0sMath::BigInt::::__ANON__[:130]Math::BigInt::__ANON__[:130]
0000s0sMath::BigInt::::__ANON__[:133]Math::BigInt::__ANON__[:133]
0000s0sMath::BigInt::::__ANON__[:137]Math::BigInt::__ANON__[:137]
0000s0sMath::BigInt::::__ANON__[:138]Math::BigInt::__ANON__[:138]
0000s0sMath::BigInt::::__ANON__[:147]Math::BigInt::__ANON__[:147]
0000s0sMath::BigInt::::__ANON__[:151]Math::BigInt::__ANON__[:151]
0000s0sMath::BigInt::::__ANON__[:152]Math::BigInt::__ANON__[:152]
0000s0sMath::BigInt::::__ANON__[:2703]Math::BigInt::__ANON__[:2703]
0000s0sMath::BigInt::::__ANON__[:44]Math::BigInt::__ANON__[:44]
0000s0sMath::BigInt::::__ANON__[:49]Math::BigInt::__ANON__[:49]
0000s0sMath::BigInt::::__ANON__[:50]Math::BigInt::__ANON__[:50]
0000s0sMath::BigInt::::__ANON__[:51]Math::BigInt::__ANON__[:51]
0000s0sMath::BigInt::::__ANON__[:52]Math::BigInt::__ANON__[:52]
0000s0sMath::BigInt::::__ANON__[:53]Math::BigInt::__ANON__[:53]
0000s0sMath::BigInt::::__ANON__[:54]Math::BigInt::__ANON__[:54]
0000s0sMath::BigInt::::__ANON__[:55]Math::BigInt::__ANON__[:55]
0000s0sMath::BigInt::::__ANON__[:56]Math::BigInt::__ANON__[:56]
0000s0sMath::BigInt::::__ANON__[:58]Math::BigInt::__ANON__[:58]
0000s0sMath::BigInt::::__ANON__[:59]Math::BigInt::__ANON__[:59]
0000s0sMath::BigInt::::__ANON__[:60]Math::BigInt::__ANON__[:60]
0000s0sMath::BigInt::::__ANON__[:70]Math::BigInt::__ANON__[:70]
0000s0sMath::BigInt::::__ANON__[:78]Math::BigInt::__ANON__[:78]
0000s0sMath::BigInt::::__ANON__[:82]Math::BigInt::__ANON__[:82]
0000s0sMath::BigInt::::__ANON__[:84]Math::BigInt::__ANON__[:84]
0000s0sMath::BigInt::::__ANON__[:85]Math::BigInt::__ANON__[:85]
0000s0sMath::BigInt::::__ANON__[:88]Math::BigInt::__ANON__[:88]
0000s0sMath::BigInt::::__ANON__[:95]Math::BigInt::__ANON__[:95]
0000s0sMath::BigInt::::__ANON__[:96]Math::BigInt::__ANON__[:96]
0000s0sMath::BigInt::::__ANON__[:97]Math::BigInt::__ANON__[:97]
0000s0sMath::BigInt::::__ANON__[:98]Math::BigInt::__ANON__[:98]
0000s0sMath::BigInt::::__ANON__[:99]Math::BigInt::__ANON__[:99]
0000s0sMath::BigInt::::__lcmMath::BigInt::__lcm
0000s0sMath::BigInt::::_div_infMath::BigInt::_div_inf
0000s0sMath::BigInt::::_find_round_parametersMath::BigInt::_find_round_parameters
0000s0sMath::BigInt::::_register_callbackMath::BigInt::_register_callback
0000s0sMath::BigInt::::_scale_aMath::BigInt::_scale_a
0000s0sMath::BigInt::::_scale_pMath::BigInt::_scale_p
0000s0sMath::BigInt::::_scan_for_nonzeroMath::BigInt::_scan_for_nonzero
0000s0sMath::BigInt::::_splitMath::BigInt::_split
0000s0sMath::BigInt::::_trailing_zerosMath::BigInt::_trailing_zeros
0000s0sMath::BigInt::::accuracyMath::BigInt::accuracy
0000s0sMath::BigInt::::as_binMath::BigInt::as_bin
0000s0sMath::BigInt::::as_hexMath::BigInt::as_hex
0000s0sMath::BigInt::::as_numberMath::BigInt::as_number
0000s0sMath::BigInt::::as_octMath::BigInt::as_oct
0000s0sMath::BigInt::::babsMath::BigInt::babs
0000s0sMath::BigInt::::bacmpMath::BigInt::bacmp
0000s0sMath::BigInt::::baddMath::BigInt::badd
0000s0sMath::BigInt::::bandMath::BigInt::band
0000s0sMath::BigInt::::batanMath::BigInt::batan
0000s0sMath::BigInt::::batan2Math::BigInt::batan2
0000s0sMath::BigInt::::bceilMath::BigInt::bceil
0000s0sMath::BigInt::::bcmpMath::BigInt::bcmp
0000s0sMath::BigInt::::bcosMath::BigInt::bcos
0000s0sMath::BigInt::::bdecMath::BigInt::bdec
0000s0sMath::BigInt::::bdivMath::BigInt::bdiv
0000s0sMath::BigInt::::bexpMath::BigInt::bexp
0000s0sMath::BigInt::::bfacMath::BigInt::bfac
0000s0sMath::BigInt::::bfloorMath::BigInt::bfloor
0000s0sMath::BigInt::::bfroundMath::BigInt::bfround
0000s0sMath::BigInt::::bgcdMath::BigInt::bgcd
0000s0sMath::BigInt::::bincMath::BigInt::binc
0000s0sMath::BigInt::::binfMath::BigInt::binf
0000s0sMath::BigInt::::biorMath::BigInt::bior
0000s0sMath::BigInt::::blcmMath::BigInt::blcm
0000s0sMath::BigInt::::blogMath::BigInt::blog
0000s0sMath::BigInt::::bmodMath::BigInt::bmod
0000s0sMath::BigInt::::bmodinvMath::BigInt::bmodinv
0000s0sMath::BigInt::::bmodpowMath::BigInt::bmodpow
0000s0sMath::BigInt::::bmulMath::BigInt::bmul
0000s0sMath::BigInt::::bmuladdMath::BigInt::bmuladd
0000s0sMath::BigInt::::bnanMath::BigInt::bnan
0000s0sMath::BigInt::::bnegMath::BigInt::bneg
0000s0sMath::BigInt::::bnokMath::BigInt::bnok
0000s0sMath::BigInt::::bnormMath::BigInt::bnorm
0000s0sMath::BigInt::::bnotMath::BigInt::bnot
0000s0sMath::BigInt::::boneMath::BigInt::bone
0000s0sMath::BigInt::::bpiMath::BigInt::bpi
0000s0sMath::BigInt::::bpowMath::BigInt::bpow
0000s0sMath::BigInt::::brootMath::BigInt::broot
0000s0sMath::BigInt::::broundMath::BigInt::bround
0000s0sMath::BigInt::::brsftMath::BigInt::brsft
0000s0sMath::BigInt::::bsinMath::BigInt::bsin
0000s0sMath::BigInt::::bsqrtMath::BigInt::bsqrt
0000s0sMath::BigInt::::bsstrMath::BigInt::bsstr
0000s0sMath::BigInt::::bstrMath::BigInt::bstr
0000s0sMath::BigInt::::bsubMath::BigInt::bsub
0000s0sMath::BigInt::::bxorMath::BigInt::bxor
0000s0sMath::BigInt::::bzeroMath::BigInt::bzero
0000s0sMath::BigInt::::configMath::BigInt::config
0000s0sMath::BigInt::::copyMath::BigInt::copy
0000s0sMath::BigInt::::digitMath::BigInt::digit
0000s0sMath::BigInt::::div_scaleMath::BigInt::div_scale
0000s0sMath::BigInt::::downgradeMath::BigInt::downgrade
0000s0sMath::BigInt::::exponentMath::BigInt::exponent
0000s0sMath::BigInt::::from_binMath::BigInt::from_bin
0000s0sMath::BigInt::::from_hexMath::BigInt::from_hex
0000s0sMath::BigInt::::from_octMath::BigInt::from_oct
0000s0sMath::BigInt::::froundMath::BigInt::fround
0000s0sMath::BigInt::::is_evenMath::BigInt::is_even
0000s0sMath::BigInt::::is_infMath::BigInt::is_inf
0000s0sMath::BigInt::::is_intMath::BigInt::is_int
0000s0sMath::BigInt::::is_nanMath::BigInt::is_nan
0000s0sMath::BigInt::::is_negativeMath::BigInt::is_negative
0000s0sMath::BigInt::::is_oddMath::BigInt::is_odd
0000s0sMath::BigInt::::is_oneMath::BigInt::is_one
0000s0sMath::BigInt::::is_positiveMath::BigInt::is_positive
0000s0sMath::BigInt::::lengthMath::BigInt::length
0000s0sMath::BigInt::::mantissaMath::BigInt::mantissa
0000s0sMath::BigInt::::numifyMath::BigInt::numify
0000s0sMath::BigInt::::objectifyMath::BigInt::objectify
0000s0sMath::BigInt::::partsMath::BigInt::parts
0000s0sMath::BigInt::::precisionMath::BigInt::precision
0000s0sMath::BigInt::::signMath::BigInt::sign
0000s0sMath::BigInt::::upgradeMath::BigInt::upgrade
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1package Math::BigInt;
2
3#
4# "Mike had an infinite amount to do and a negative amount of time in which
5# to do it." - Before and After
6#
7
8# The following hash values are used:
9# value: unsigned int with actual value (as a Math::BigInt::Calc or similar)
10# sign : +,-,NaN,+inf,-inf
11# _a : accuracy
12# _p : precision
13# _f : flags, used by MBF to flag parts of a float as untouchable
14
15# Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since
16# underlying lib might change the reference!
17
1812µsmy $class = "Math::BigInt";
192177µs144µs
# spent 44µs within Math::BigInt::BEGIN@19 which was called: # once (44µs+0s) by bigint::import at line 19
use 5.006002;
# spent 44µs making 1 call to Math::BigInt::BEGIN@19
20
211600ns$VERSION = '1.994';
22
23115µs@ISA = qw(Exporter);
2412µs@EXPORT_OK = qw(objectify bgcd blcm);
25
26# _trap_inf and _trap_nan are internal and should never be accessed from the
27# outside
281210µs
# spent 226µs (16+210) within Math::BigInt::BEGIN@28 which was called: # once (16µs+210µs) by bigint::import at line 29
use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode
# spent 210µs making 1 call to vars::import
29260µs1226µs $upgrade $downgrade $_trap_nan $_trap_inf/;
# spent 226µs making 1 call to Math::BigInt::BEGIN@28
3022.45ms229µs
# spent 23µs (16+7) within Math::BigInt::BEGIN@30 which was called: # once (16µs+7µs) by bigint::import at line 30
use strict;
# spent 23µs making 1 call to Math::BigInt::BEGIN@30 # spent 7µs making 1 call to strict::import
31
32# Inside overload, the first arg is always an object. If the original code had
33# it reversed (like $x = 2 * $y), then the third parameter is true.
34# In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes
35# no difference, but in some cases it does.
36
37# For overloaded ops with only one argument we simple use $_[0]->copy() to
38# preserve the argument.
39
40# Thus inheritance of overload operators becomes possible and transparent for
41# our subclasses without the need to repeat the entire overload section there.
42
43use overload
44
# spent 1.08ms (137µs+947µs) within Math::BigInt::BEGIN@44 which was called: # once (137µs+947µs) by bigint::import at line 153
'=' => sub { $_[0]->copy(); },
45
46# some shortcuts for speed (assumes that reversed order of arguments is routed
47# to normal '+' and we thus can always modify first arg. If this is changed,
48# this breaks and must be adjusted.)
49'+=' => sub { $_[0]->badd($_[1]); },
50'-=' => sub { $_[0]->bsub($_[1]); },
51'*=' => sub { $_[0]->bmul($_[1]); },
52'/=' => sub { scalar $_[0]->bdiv($_[1]); },
53'%=' => sub { $_[0]->bmod($_[1]); },
54'^=' => sub { $_[0]->bxor($_[1]); },
55'&=' => sub { $_[0]->band($_[1]); },
56'|=' => sub { $_[0]->bior($_[1]); },
57
58'**=' => sub { $_[0]->bpow($_[1]); },
59'<<=' => sub { $_[0]->blsft($_[1]); },
60'>>=' => sub { $_[0]->brsft($_[1]); },
61
62# not supported by Perl yet
63'..' => \&_pointpoint,
64
65'<=>' => sub { my $rc = $_[2] ?
66 ref($_[0])->bcmp($_[1],$_[0]) :
67 $_[0]->bcmp($_[1]);
68 $rc = 1 unless defined $rc;
69 $rc <=> 0;
70 },
71# we need '>=' to get things like "1 >= NaN" right:
72'>=' => sub { my $rc = $_[2] ?
73 ref($_[0])->bcmp($_[1],$_[0]) :
74 $_[0]->bcmp($_[1]);
75 # if there was a NaN involved, return false
76 return '' unless defined $rc;
77 $rc >= 0;
78 },
79'cmp' => sub {
80 $_[2] ?
81 "$_[1]" cmp $_[0]->bstr() :
82 $_[0]->bstr() cmp "$_[1]" },
83
84'cos' => sub { $_[0]->copy->bcos(); },
85'sin' => sub { $_[0]->copy->bsin(); },
86'atan2' => sub { $_[2] ?
87 ref($_[0])->new($_[1])->batan2($_[0]) :
88 $_[0]->copy()->batan2($_[1]) },
89
90# are not yet overloadable
91#'hex' => sub { print "hex"; $_[0]; },
92#'oct' => sub { print "oct"; $_[0]; },
93
94# log(N) is log(N, e), where e is Euler's number
95'log' => sub { $_[0]->copy()->blog($_[1], undef); },
96'exp' => sub { $_[0]->copy()->bexp($_[1]); },
97'int' => sub { $_[0]->copy(); },
98'neg' => sub { $_[0]->copy()->bneg(); },
99'abs' => sub { $_[0]->copy()->babs(); },
100'sqrt' => sub { $_[0]->copy()->bsqrt(); },
101'~' => sub { $_[0]->copy()->bnot(); },
102
103# for subtract it's a bit tricky to not modify b: b-a => -a+b
104'-' => sub { my $c = $_[0]->copy; $_[2] ?
105 $c->bneg()->badd( $_[1]) :
106 $c->bsub( $_[1]) },
107'+' => sub { $_[0]->copy()->badd($_[1]); },
108'*' => sub { $_[0]->copy()->bmul($_[1]); },
109
110'/' => sub {
111 $_[2] ? ref($_[0])->new($_[1])->bdiv($_[0]) : $_[0]->copy->bdiv($_[1]);
112 },
113'%' => sub {
114 $_[2] ? ref($_[0])->new($_[1])->bmod($_[0]) : $_[0]->copy->bmod($_[1]);
115 },
116'**' => sub {
117 $_[2] ? ref($_[0])->new($_[1])->bpow($_[0]) : $_[0]->copy->bpow($_[1]);
118 },
119
# spent 291µs (16+275) within Math::BigInt::__ANON__[/usr/share/perl/5.14/Math/BigInt.pm:121] which was called 2 times, avg 145µs/call: # once (11µs+159µs) by main::BEGIN@7 at line 2051 of Value/Convertor.pm # once (6µs+116µs) by main::BEGIN@7 at line 2072 of Value/Convertor.pm
'<<' => sub {
120211µs4275µs $_[2] ? ref($_[0])->new($_[1])->blsft($_[0]) : $_[0]->copy->blsft($_[1]);
# spent 218µs making 2 calls to Math::BigInt::blsft, avg 109µs/call # spent 57µs making 2 calls to Math::BigInt::new, avg 29µs/call
121 },
122'>>' => sub {
123 $_[2] ? ref($_[0])->new($_[1])->brsft($_[0]) : $_[0]->copy->brsft($_[1]);
124 },
125'&' => sub {
126 $_[2] ? ref($_[0])->new($_[1])->band($_[0]) : $_[0]->copy->band($_[1]);
127 },
128'|' => sub {
129 $_[2] ? ref($_[0])->new($_[1])->bior($_[0]) : $_[0]->copy->bior($_[1]);
130 },
131'^' => sub {
132 $_[2] ? ref($_[0])->new($_[1])->bxor($_[0]) : $_[0]->copy->bxor($_[1]);
133 },
134
135# can modify arg of ++ and --, so avoid a copy() for speed, but don't
136# use $_[0]->bone(), it would modify $_[0] to be 1!
137'++' => sub { $_[0]->binc() },
138'--' => sub { $_[0]->bdec() },
139
140# if overloaded, O(1) instead of O(N) and twice as fast for small numbers
141'bool' => sub {
142 # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
143 # v5.6.1 dumps on this: return !$_[0]->is_zero() || undef; :-(
144 my $t = undef;
145 $t = 1 if !$_[0]->is_zero();
146 $t;
147 },
148
149# the original qw() does not work with the TIESCALAR below, why?
150# Order of arguments unsignificant
151'""' => sub { $_[0]->bstr(); },
152'0+' => sub { $_[0]->numify(); }
1532500µs22.03ms;
# spent 1.08ms making 1 call to Math::BigInt::BEGIN@44 # spent 947µs making 1 call to overload::import
154
155##############################################################################
156# global constants, flags and accessory
157
158# These vars are public, but their direct usage is not recommended, use the
159# accessor methods instead
160
1611700ns$round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
1621500ns$accuracy = undef;
1631200ns$precision = undef;
1641600ns$div_scale = 40;
165
1661300ns$upgrade = undef; # default is no upgrade
1671200ns$downgrade = undef; # default is no downgrade
168
169# These are internally, and not to be used from the outside at all
170
1711200ns$_trap_nan = 0; # are NaNs ok? set w/ config()
1721200ns$_trap_inf = 0; # are infs ok? set w/ config()
1731800nsmy $nan = 'NaN'; # constants for easier life
174
1751600nsmy $CALC = 'Math::BigInt::Calc'; # module to do the low level math
176 # default is Calc.pm
1771200nsmy $IMPORT = 0; # was import() called yet?
178 # used to make require work
1791300nsmy %WARN; # warn only once for low-level libs
1801300nsmy %CAN; # cache for $CALC->can(...)
1811100nsmy %CALLBACKS; # callbacks to notify on lib loads
1821900nsmy $EMU_LIB = 'Math/BigInt/CalcEmu.pm'; # emulate low-level math
183
184##############################################################################
185# the old code had $rnd_mode, so we need to support it, too
186
187110µs159µs$rnd_mode = 'even';
# spent 59µs making 1 call to Math::BigInt::STORE
188253µs
# spent 46µs within Math::BigInt::TIESCALAR which was called: # once (46µs+0s) by Math::BigInt::BEGIN@193 at line 195
sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; }
189sub FETCH { return $round_mode; }
190110µs146µs
# spent 59µs (13+46) within Math::BigInt::STORE which was called: # once (13µs+46µs) by bigint::import at line 187
sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); }
# spent 46µs making 1 call to Math::BigInt::round_mode
191
192BEGIN
193
# spent 92µs (46+46) within Math::BigInt::BEGIN@193 which was called: # once (46µs+46µs) by bigint::import at line 201
{
194 # tie to enable $rnd_mode to work transparently
195436µs146µs tie $rnd_mode, 'Math::BigInt';
# spent 46µs making 1 call to Math::BigInt::TIESCALAR
196
197 # set up some handy alias names
198 *as_int = \&as_number;
199 *is_pos = \&is_positive;
200 *is_neg = \&is_negative;
201156µs192µs }
# spent 92µs making 1 call to Math::BigInt::BEGIN@193
202
203##############################################################################
204
205sub round_mode
206
# spent 46µs (39+7) within Math::BigInt::round_mode which was called: # once (39µs+7µs) by Math::BigInt::STORE at line 190
{
2072287µs262µs
# spent 38µs (15+23) within Math::BigInt::BEGIN@207 which was called: # once (15µs+23µs) by bigint::import at line 207
no strict 'refs';
# spent 38µs making 1 call to Math::BigInt::BEGIN@207 # spent 23µs making 1 call to strict::unimport
208 # make Class->round_mode() work
20933µs my $self = shift;
210 my $class = ref($self) || $self || __PACKAGE__;
211345µs if (defined $_[0])
212 {
213 my $m = shift;
21417µs if ($m !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
# spent 7µs making 1 call to Math::BigInt::CORE:match
215 {
216 require Carp; Carp::croak ("Unknown round mode '$m'");
217 }
21812µs return ${"${class}::round_mode"} = $m;
219 }
220 ${"${class}::round_mode"};
221 }
222
223sub upgrade
224 {
2252167µs260µs
# spent 38µs (16+22) within Math::BigInt::BEGIN@225 which was called: # once (16µs+22µs) by bigint::import at line 225
no strict 'refs';
# spent 38µs making 1 call to Math::BigInt::BEGIN@225 # spent 22µs making 1 call to strict::unimport
226 # make Class->upgrade() work
227 my $self = shift;
228 my $class = ref($self) || $self || __PACKAGE__;
229 # need to set new value?
230 if (@_ > 0)
231 {
232 return ${"${class}::upgrade"} = $_[0];
233 }
234 ${"${class}::upgrade"};
235 }
236
237sub downgrade
238 {
2392181µs259µs
# spent 39µs (18+20) within Math::BigInt::BEGIN@239 which was called: # once (18µs+20µs) by bigint::import at line 239
no strict 'refs';
# spent 39µs making 1 call to Math::BigInt::BEGIN@239 # spent 20µs making 1 call to strict::unimport
240 # make Class->downgrade() work
241 my $self = shift;
242 my $class = ref($self) || $self || __PACKAGE__;
243 # need to set new value?
244 if (@_ > 0)
245 {
246 return ${"${class}::downgrade"} = $_[0];
247 }
248 ${"${class}::downgrade"};
249 }
250
251sub div_scale
252 {
2532294µs254µs
# spent 34µs (14+20) within Math::BigInt::BEGIN@253 which was called: # once (14µs+20µs) by bigint::import at line 253
no strict 'refs';
# spent 34µs making 1 call to Math::BigInt::BEGIN@253 # spent 20µs making 1 call to strict::unimport
254 # make Class->div_scale() work
255 my $self = shift;
256 my $class = ref($self) || $self || __PACKAGE__;
257 if (defined $_[0])
258 {
259 if ($_[0] < 0)
260 {
261 require Carp; Carp::croak ('div_scale must be greater than zero');
262 }
263 ${"${class}::div_scale"} = $_[0];
264 }
265 ${"${class}::div_scale"};
266 }
267
268sub accuracy
269 {
270 # $x->accuracy($a); ref($x) $a
271 # $x->accuracy(); ref($x)
272 # Class->accuracy(); class
273 # Class->accuracy($a); class $a
274
275 my $x = shift;
276 my $class = ref($x) || $x || __PACKAGE__;
277
2782448µs257µs
# spent 36µs (15+21) within Math::BigInt::BEGIN@278 which was called: # once (15µs+21µs) by bigint::import at line 278
no strict 'refs';
# spent 36µs making 1 call to Math::BigInt::BEGIN@278 # spent 21µs making 1 call to strict::unimport
279 # need to set new value?
280 if (@_ > 0)
281 {
282 my $a = shift;
283 # convert objects to scalars to avoid deep recursion. If object doesn't
284 # have numify(), then hopefully it will have overloading for int() and
285 # boolean test without wandering into a deep recursion path...
286 $a = $a->numify() if ref($a) && $a->can('numify');
287
288 if (defined $a)
289 {
290 # also croak on non-numerical
291 if (!$a || $a <= 0)
292 {
293 require Carp;
294 Carp::croak ('Argument to accuracy must be greater than zero');
295 }
296 if (int($a) != $a)
297 {
298 require Carp;
299 Carp::croak ('Argument to accuracy must be an integer');
300 }
301 }
302 if (ref($x))
303 {
304 # $object->accuracy() or fallback to global
305 $x->bround($a) if $a; # not for undef, 0
306 $x->{_a} = $a; # set/overwrite, even if not rounded
307 delete $x->{_p}; # clear P
308 $a = ${"${class}::accuracy"} unless defined $a; # proper return value
309 }
310 else
311 {
312 ${"${class}::accuracy"} = $a; # set global A
313 ${"${class}::precision"} = undef; # clear global P
314 }
315 return $a; # shortcut
316 }
317
318 my $a;
319 # $object->accuracy() or fallback to global
320 $a = $x->{_a} if ref($x);
321 # but don't return global undef, when $x's accuracy is 0!
322 $a = ${"${class}::accuracy"} if !defined $a;
323 $a;
324 }
325
326sub precision
327 {
328 # $x->precision($p); ref($x) $p
329 # $x->precision(); ref($x)
330 # Class->precision(); class
331 # Class->precision($p); class $p
332
333 my $x = shift;
334 my $class = ref($x) || $x || __PACKAGE__;
335
3362411µs264µs
# spent 42µs (21+21) within Math::BigInt::BEGIN@336 which was called: # once (21µs+21µs) by bigint::import at line 336
no strict 'refs';
# spent 42µs making 1 call to Math::BigInt::BEGIN@336 # spent 21µs making 1 call to strict::unimport
337 if (@_ > 0)
338 {
339 my $p = shift;
340 # convert objects to scalars to avoid deep recursion. If object doesn't
341 # have numify(), then hopefully it will have overloading for int() and
342 # boolean test without wandering into a deep recursion path...
343 $p = $p->numify() if ref($p) && $p->can('numify');
344 if ((defined $p) && (int($p) != $p))
345 {
346 require Carp; Carp::croak ('Argument to precision must be an integer');
347 }
348 if (ref($x))
349 {
350 # $object->precision() or fallback to global
351 $x->bfround($p) if $p; # not for undef, 0
352 $x->{_p} = $p; # set/overwrite, even if not rounded
353 delete $x->{_a}; # clear A
354 $p = ${"${class}::precision"} unless defined $p; # proper return value
355 }
356 else
357 {
358 ${"${class}::precision"} = $p; # set global P
359 ${"${class}::accuracy"} = undef; # clear global A
360 }
361 return $p; # shortcut
362 }
363
364 my $p;
365 # $object->precision() or fallback to global
366 $p = $x->{_p} if ref($x);
367 # but don't return global undef, when $x's precision is 0!
368 $p = ${"${class}::precision"} if !defined $p;
369 $p;
370 }
371
372sub config
373 {
374 # return (or set) configuration data as hash ref
375 my $class = shift || 'Math::BigInt';
376
3772717µs259µs
# spent 37µs (15+22) within Math::BigInt::BEGIN@377 which was called: # once (15µs+22µs) by bigint::import at line 377
no strict 'refs';
# spent 37µs making 1 call to Math::BigInt::BEGIN@377 # spent 22µs making 1 call to strict::unimport
378 if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH')))
379 {
380 # try to set given options as arguments from hash
381
382 my $args = $_[0];
383 if (ref($args) ne 'HASH')
384 {
385 $args = { @_ };
386 }
387 # these values can be "set"
388 my $set_args = {};
389 foreach my $key (
390 qw/trap_inf trap_nan
391 upgrade downgrade precision accuracy round_mode div_scale/
392 )
393 {
394 $set_args->{$key} = $args->{$key} if exists $args->{$key};
395 delete $args->{$key};
396 }
397 if (keys %$args > 0)
398 {
399 require Carp;
400 Carp::croak ("Illegal key(s) '",
401 join("','",keys %$args),"' passed to $class\->config()");
402 }
403 foreach my $key (keys %$set_args)
404 {
405 if ($key =~ /^trap_(inf|nan)\z/)
406 {
407 ${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0);
408 next;
409 }
410 # use a call instead of just setting the $variable to check argument
411 $class->$key($set_args->{$key});
412 }
413 }
414
415 # now return actual configuration
416
417 my $cfg = {
418 lib => $CALC,
419 lib_version => ${"${CALC}::VERSION"},
420 class => $class,
421 trap_nan => ${"${class}::_trap_nan"},
422 trap_inf => ${"${class}::_trap_inf"},
423 version => ${"${class}::VERSION"},
424 };
425 foreach my $key (qw/
426 upgrade downgrade precision accuracy round_mode div_scale
427 /)
428 {
429 $cfg->{$key} = ${"${class}::$key"};
430 };
431 if (@_ == 1 && (ref($_[0]) ne 'HASH'))
432 {
433 # calls of the style config('lib') return just this value
434 return $cfg->{$_[0]};
435 }
436 $cfg;
437 }
438
439sub _scale_a
440 {
441 # select accuracy parameter based on precedence,
442 # used by bround() and bfround(), may return undef for scale (means no op)
443 my ($x,$scale,$mode) = @_;
444
445 $scale = $x->{_a} unless defined $scale;
446
4472245µs262µs
# spent 39µs (16+23) within Math::BigInt::BEGIN@447 which was called: # once (16µs+23µs) by bigint::import at line 447
no strict 'refs';
# spent 39µs making 1 call to Math::BigInt::BEGIN@447 # spent 23µs making 1 call to strict::unimport
448 my $class = ref($x);
449
450 $scale = ${ $class . '::accuracy' } unless defined $scale;
451 $mode = ${ $class . '::round_mode' } unless defined $mode;
452
453 if (defined $scale)
454 {
455 $scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale);
456 $scale = int($scale);
457 }
458
459 ($scale,$mode);
460 }
461
462sub _scale_p
463 {
464 # select precision parameter based on precedence,
465 # used by bround() and bfround(), may return undef for scale (means no op)
466 my ($x,$scale,$mode) = @_;
467
468 $scale = $x->{_p} unless defined $scale;
469
4702774µs254µs
# spent 34µs (14+20) within Math::BigInt::BEGIN@470 which was called: # once (14µs+20µs) by bigint::import at line 470
no strict 'refs';
# spent 34µs making 1 call to Math::BigInt::BEGIN@470 # spent 20µs making 1 call to strict::unimport
471 my $class = ref($x);
472
473 $scale = ${ $class . '::precision' } unless defined $scale;
474 $mode = ${ $class . '::round_mode' } unless defined $mode;
475
476 if (defined $scale)
477 {
478 $scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale);
479 $scale = int($scale);
480 }
481
482 ($scale,$mode);
483 }
484
485##############################################################################
486# constructors
487
488sub copy
489 {
490 # if two arguments, the first one is the class to "swallow" subclasses
491 if (@_ > 1)
492 {
493 my $self = bless {
494 sign => $_[1]->{sign},
495 value => $CALC->_copy($_[1]->{value}),
496 }, $_[0] if @_ > 1;
497
498 $self->{_a} = $_[1]->{_a} if defined $_[1]->{_a};
499 $self->{_p} = $_[1]->{_p} if defined $_[1]->{_p};
500 return $self;
501 }
502
503 my $self = bless {
504 sign => $_[0]->{sign},
505 value => $CALC->_copy($_[0]->{value}),
506 }, ref($_[0]);
507
508 $self->{_a} = $_[0]->{_a} if defined $_[0]->{_a};
509 $self->{_p} = $_[0]->{_p} if defined $_[0]->{_p};
510 $self;
511 }
512
513sub new
514
# spent 453µs (362+92) within Math::BigInt::new which was called 10 times, avg 45µs/call: # 8 times (336µs+61µs) by Math::BigInt::__ANON__[/usr/share/perl/5.14/Math/BigInt.pm:2702] at line 2702, avg 50µs/call # 2 times (26µs+31µs) by Math::BigInt::__ANON__[/usr/share/perl/5.14/Math/BigInt.pm:121] at line 120, avg 29µs/call
{
515 # create a new BigInt object from a string or another BigInt object.
516 # see hash keys documented at top
517
518 # the argument could be an object, so avoid ||, && etc on it, this would
519 # cause costly overloaded code to be called. The only allowed ops are
520 # ref() and defined.
521
52260264µs my ($class,$wanted,$a,$p,$r) = @_;
523
524 # avoid numify-calls by not using || on $wanted!
525 return $class->bzero($a,$p) if !defined $wanted; # default to 0
526 return $class->copy($wanted,$a,$p,$r)
527 if ref($wanted) && $wanted->isa($class); # MBI or subclass
528
529 $class->import() if $IMPORT == 0; # make require work
530
531 my $self = bless {}, $class;
532
533 # shortcut for "normal" numbers
53440117µs1030µs if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*\z/))
# spent 30µs making 10 calls to Math::BigInt::CORE:match, avg 3µs/call
535 {
536 $self->{sign} = $1 || '+';
537
5381024µs108µs if ($wanted =~ /^[+-]/)
# spent 8µs making 10 calls to Math::BigInt::CORE:match, avg 820ns/call
539 {
540 # remove sign without touching wanted to make it work with constants
541 my $t = $wanted; $t =~ s/^[+-]//;
542 $self->{value} = $CALC->_new($t);
543 }
544 else
545 {
5461053µs $self->{value} = $CALC->_new($wanted);
# spent 53µs making 10 calls to Math::BigInt::Calc::_new, avg 5µs/call
547 }
54821.10ms260µs
# spent 38µs (15+22) within Math::BigInt::BEGIN@548 which was called: # once (15µs+22µs) by bigint::import at line 548
no strict 'refs';
# spent 38µs making 1 call to Math::BigInt::BEGIN@548 # spent 22µs making 1 call to strict::unimport
549208µs if ( (defined $a) || (defined $p)
550 || (defined ${"${class}::precision"})
551 || (defined ${"${class}::accuracy"})
552 )
553 {
554 $self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
555 }
556 return $self;
557 }
558
559 # handle '+inf', '-inf' first
560 if ($wanted =~ /^[+-]?inf\z/)
561 {
562 $self->{sign} = $wanted; # set a default sign for bstr()
563 return $self->binf($wanted);
564 }
565 # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
566 my ($mis,$miv,$mfv,$es,$ev) = _split($wanted);
567 if (!ref $mis)
568 {
569 if ($_trap_nan)
570 {
571 require Carp; Carp::croak("$wanted is not a number in $class");
572 }
573 $self->{value} = $CALC->_zero();
574 $self->{sign} = $nan;
575 return $self;
576 }
577 if (!ref $miv)
578 {
579 # _from_hex or _from_bin
580 $self->{value} = $mis->{value};
581 $self->{sign} = $mis->{sign};
582 return $self; # throw away $mis
583 }
584 # make integer from mantissa by adjusting exp, then convert to bigint
585 $self->{sign} = $$mis; # store sign
586 $self->{value} = $CALC->_zero(); # for all the NaN cases
587 my $e = int("$$es$$ev"); # exponent (avoid recursion)
588 if ($e > 0)
589 {
590 my $diff = $e - CORE::length($$mfv);
591 if ($diff < 0) # Not integer
592 {
593 if ($_trap_nan)
594 {
595 require Carp; Carp::croak("$wanted not an integer in $class");
596 }
597 #print "NOI 1\n";
598 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
599 $self->{sign} = $nan;
600 }
601 else # diff >= 0
602 {
603 # adjust fraction and add it to value
604 #print "diff > 0 $$miv\n";
605 $$miv = $$miv . ($$mfv . '0' x $diff);
606 }
607 }
608 else
609 {
610 if ($$mfv ne '') # e <= 0
611 {
612 # fraction and negative/zero E => NOI
613 if ($_trap_nan)
614 {
615 require Carp; Carp::croak("$wanted not an integer in $class");
616 }
617 #print "NOI 2 \$\$mfv '$$mfv'\n";
618 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
619 $self->{sign} = $nan;
620 }
621 elsif ($e < 0)
622 {
623 # xE-y, and empty mfv
624 #print "xE-y\n";
625 $e = abs($e);
626 if ($$miv !~ s/0{$e}$//) # can strip so many zero's?
627 {
628 if ($_trap_nan)
629 {
630 require Carp; Carp::croak("$wanted not an integer in $class");
631 }
632 #print "NOI 3\n";
633 return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
634 $self->{sign} = $nan;
635 }
636 }
637 }
638 $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0
639 $self->{value} = $CALC->_new($$miv) if $self->{sign} =~ /^[+-]$/;
640 # if any of the globals is set, use them to round and store them inside $self
641 # do not round for new($x,undef,undef) since that is used by MBF to signal
642 # no rounding
643 $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
644 $self;
645 }
646
647sub bnan
648 {
649 # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
650 my $self = shift;
651 $self = $class if !defined $self;
652 if (!ref($self))
653 {
654 my $c = $self; $self = {}; bless $self, $c;
655 }
6562395µs263µs
# spent 39µs (16+23) within Math::BigInt::BEGIN@656 which was called: # once (16µs+23µs) by bigint::import at line 656
no strict 'refs';
# spent 39µs making 1 call to Math::BigInt::BEGIN@656 # spent 23µs making 1 call to strict::unimport
657 if (${"${class}::_trap_nan"})
658 {
659 require Carp;
660 Carp::croak ("Tried to set $self to NaN in $class\::bnan()");
661 }
662 $self->import() if $IMPORT == 0; # make require work
663 return if $self->modify('bnan');
664 if ($self->can('_bnan'))
665 {
666 # use subclass to initialize
667 $self->_bnan();
668 }
669 else
670 {
671 # otherwise do our own thing
672 $self->{value} = $CALC->_zero();
673 }
674 $self->{sign} = $nan;
675 delete $self->{_a}; delete $self->{_p}; # rounding NaN is silly
676 $self;
677 }
678
679sub binf
680 {
681 # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
682 # the sign is either '+', or if given, used from there
683 my $self = shift;
684 my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
685 $self = $class if !defined $self;
686 if (!ref($self))
687 {
688 my $c = $self; $self = {}; bless $self, $c;
689 }
69021.71ms260µs
# spent 38µs (15+22) within Math::BigInt::BEGIN@690 which was called: # once (15µs+22µs) by bigint::import at line 690
no strict 'refs';
# spent 38µs making 1 call to Math::BigInt::BEGIN@690 # spent 22µs making 1 call to strict::unimport
691 if (${"${class}::_trap_inf"})
692 {
693 require Carp;
694 Carp::croak ("Tried to set $self to +-inf in $class\::binf()");
695 }
696 $self->import() if $IMPORT == 0; # make require work
697 return if $self->modify('binf');
698 if ($self->can('_binf'))
699 {
700 # use subclass to initialize
701 $self->_binf();
702 }
703 else
704 {
705 # otherwise do our own thing
706 $self->{value} = $CALC->_zero();
707 }
708 $sign = $sign . 'inf' if $sign !~ /inf$/; # - => -inf
709 $self->{sign} = $sign;
710 ($self->{_a},$self->{_p}) = @_; # take over requested rounding
711 $self;
712 }
713
714sub bzero
715 {
716 # create a bigint '+0', if given a BigInt, set it to 0
717 my $self = shift;
718 $self = __PACKAGE__ if !defined $self;
719
720 if (!ref($self))
721 {
722 my $c = $self; $self = {}; bless $self, $c;
723 }
724 $self->import() if $IMPORT == 0; # make require work
725 return if $self->modify('bzero');
726
727 if ($self->can('_bzero'))
728 {
729 # use subclass to initialize
730 $self->_bzero();
731 }
732 else
733 {
734 # otherwise do our own thing
735 $self->{value} = $CALC->_zero();
736 }
737 $self->{sign} = '+';
738 if (@_ > 0)
739 {
740 if (@_ > 3)
741 {
742 # call like: $x->bzero($a,$p,$r,$y);
743 ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
744 }
745 else
746 {
747 $self->{_a} = $_[0]
748 if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
749 $self->{_p} = $_[1]
750 if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
751 }
752 }
753 $self;
754 }
755
756sub bone
757 {
758 # create a bigint '+1' (or -1 if given sign '-'),
759 # if given a BigInt, set it to +1 or -1, respectively
760 my $self = shift;
761 my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
762 $self = $class if !defined $self;
763
764 if (!ref($self))
765 {
766 my $c = $self; $self = {}; bless $self, $c;
767 }
768 $self->import() if $IMPORT == 0; # make require work
769 return if $self->modify('bone');
770
771 if ($self->can('_bone'))
772 {
773 # use subclass to initialize
774 $self->_bone();
775 }
776 else
777 {
778 # otherwise do our own thing
779 $self->{value} = $CALC->_one();
780 }
781 $self->{sign} = $sign;
782 if (@_ > 0)
783 {
784 if (@_ > 3)
785 {
786 # call like: $x->bone($sign,$a,$p,$r,$y);
787 ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
788 }
789 else
790 {
791 # call like: $x->bone($sign,$a,$p,$r);
792 $self->{_a} = $_[0]
793 if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
794 $self->{_p} = $_[1]
795 if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
796 }
797 }
798 $self;
799 }
800
801##############################################################################
802# string conversion
803
804sub bsstr
805 {
806 # (ref to BFLOAT or num_str ) return num_str
807 # Convert number from internal format to scientific string format.
808 # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
809 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
810
811 if ($x->{sign} !~ /^[+-]$/)
812 {
813 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
814 return 'inf'; # +inf
815 }
816 my ($m,$e) = $x->parts();
817 #$m->bstr() . 'e+' . $e->bstr(); # e can only be positive in BigInt
818 # 'e+' because E can only be positive in BigInt
819 $m->bstr() . 'e+' . $CALC->_str($e->{value});
820 }
821
822sub bstr
823 {
824 # make a string from bigint object
825 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
826
827 if ($x->{sign} !~ /^[+-]$/)
828 {
829 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN
830 return 'inf'; # +inf
831 }
832 my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
833 $es.$CALC->_str($x->{value});
834 }
835
836sub numify
837 {
838 # Make a "normal" scalar from a BigInt object
839 my $x = shift; $x = $class->new($x) unless ref $x;
840
841 return $x->bstr() if $x->{sign} !~ /^[+-]$/;
842 my $num = $CALC->_num($x->{value});
843 return -$num if $x->{sign} eq '-';
844 $num;
845 }
846
847##############################################################################
848# public stuff (usually prefixed with "b")
849
850sub sign
851 {
852 # return the sign of the number: +/-/-inf/+inf/NaN
853 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
854
855 $x->{sign};
856 }
857
858sub _find_round_parameters
859 {
860 # After any operation or when calling round(), the result is rounded by
861 # regarding the A & P from arguments, local parameters, or globals.
862
863 # !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!!
864
865 # This procedure finds the round parameters, but it is for speed reasons
866 # duplicated in round. Otherwise, it is tested by the testsuite and used
867 # by fdiv().
868
869 # returns ($self) or ($self,$a,$p,$r) - sets $self to NaN of both A and P
870 # were requested/defined (locally or globally or both)
871
872 my ($self,$a,$p,$r,@args) = @_;
873 # $a accuracy, if given by caller
874 # $p precision, if given by caller
875 # $r round_mode, if given by caller
876 # @args all 'other' arguments (0 for unary, 1 for binary ops)
877
878 my $c = ref($self); # find out class of argument(s)
8792650µs265µs
# spent 41µs (17+24) within Math::BigInt::BEGIN@879 which was called: # once (17µs+24µs) by bigint::import at line 879
no strict 'refs';
# spent 41µs making 1 call to Math::BigInt::BEGIN@879 # spent 24µs making 1 call to strict::unimport
880
881 # convert to normal scalar for speed and correctness in inner parts
882 $a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a);
883 $p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p);
884
885 # now pick $a or $p, but only if we have got "arguments"
886 if (!defined $a)
887 {
888 foreach ($self,@args)
889 {
890 # take the defined one, or if both defined, the one that is smaller
891 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
892 }
893 }
894 if (!defined $p)
895 {
896 # even if $a is defined, take $p, to signal error for both defined
897 foreach ($self,@args)
898 {
899 # take the defined one, or if both defined, the one that is bigger
900 # -2 > -3, and 3 > 2
901 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
902 }
903 }
904 # if still none defined, use globals (#2)
905 $a = ${"$c\::accuracy"} unless defined $a;
906 $p = ${"$c\::precision"} unless defined $p;
907
908 # A == 0 is useless, so undef it to signal no rounding
909 $a = undef if defined $a && $a == 0;
910
911 # no rounding today?
912 return ($self) unless defined $a || defined $p; # early out
913
914 # set A and set P is an fatal error
915 return ($self->bnan()) if defined $a && defined $p; # error
916
917 $r = ${"$c\::round_mode"} unless defined $r;
918 if ($r !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
919 {
920 require Carp; Carp::croak ("Unknown round mode '$r'");
921 }
922
923 $a = int($a) if defined $a;
924 $p = int($p) if defined $p;
925
926 ($self,$a,$p,$r);
927 }
928
929sub round
930
# spent 17µs within Math::BigInt::round which was called 2 times, avg 8µs/call: # 2 times (17µs+0s) by Math::BigInt::blsft at line 2074, avg 8µs/call
{
931 # Round $self according to given parameters, or given second argument's
932 # parameters or global defaults
933
934 # for speed reasons, _find_round_parameters is embedded here:
935
9361612µs my ($self,$a,$p,$r,@args) = @_;
937 # $a accuracy, if given by caller
938 # $p precision, if given by caller
939 # $r round_mode, if given by caller
940 # @args all 'other' arguments (0 for unary, 1 for binary ops)
941
942 my $c = ref($self); # find out class of argument(s)
943216.2ms276µs
# spent 46µs (17+30) within Math::BigInt::BEGIN@943 which was called: # once (17µs+30µs) by bigint::import at line 943
no strict 'refs';
# spent 46µs making 1 call to Math::BigInt::BEGIN@943 # spent 30µs making 1 call to strict::unimport
944
945 # now pick $a or $p, but only if we have got "arguments"
94621µs if (!defined $a)
947 {
948 foreach ($self,@args)
949 {
950 # take the defined one, or if both defined, the one that is smaller
95122µs $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
952 }
953 }
9542600ns if (!defined $p)
955 {
956 # even if $a is defined, take $p, to signal error for both defined
957 foreach ($self,@args)
958 {
959 # take the defined one, or if both defined, the one that is bigger
960 # -2 > -3, and 3 > 2
96121µs $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
962 }
963 }
964 # if still none defined, use globals (#2)
96521µs $a = ${"$c\::accuracy"} unless defined $a;
9662500ns $p = ${"$c\::precision"} unless defined $p;
967
968 # A == 0 is useless, so undef it to signal no rounding
969 $a = undef if defined $a && $a == 0;
970
971 # no rounding today?
972 return $self unless defined $a || defined $p; # early out
973
974 # set A and set P is an fatal error
975 return $self->bnan() if defined $a && defined $p;
976
977 $r = ${"$c\::round_mode"} unless defined $r;
978 if ($r !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/)
979 {
980 require Carp; Carp::croak ("Unknown round mode '$r'");
981 }
982
983 # now round, by calling either fround or ffround:
984 if (defined $a)
985 {
986 $self->bround(int($a),$r) if !defined $self->{_a} || $self->{_a} >= $a;
987 }
988 else # both can't be undefined due to early out
989 {
990 $self->bfround(int($p),$r) if !defined $self->{_p} || $self->{_p} <= $p;
991 }
992 # bround() or bfround() already called bnorm() if nec.
993 $self;
994 }
995
996sub bnorm
997 {
998 # (numstr or BINT) return BINT
999 # Normalize number -- no-op here
1000 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1001 $x;
1002 }
1003
1004sub babs
1005 {
1006 # (BINT or num_str) return BINT
1007 # make number absolute, or return absolute BINT from string
1008 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1009
1010 return $x if $x->modify('babs');
1011 # post-normalized abs for internal use (does nothing for NaN)
1012 $x->{sign} =~ s/^-/+/;
1013 $x;
1014 }
1015
1016sub bneg
1017 {
1018 # (BINT or num_str) return BINT
1019 # negate number or make a negated number from string
1020 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1021
1022 return $x if $x->modify('bneg');
1023
1024 # for +0 dont negate (to have always normalized +0). Does nothing for 'NaN'
1025 $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $CALC->_is_zero($x->{value}));
1026 $x;
1027 }
1028
1029sub bcmp
1030 {
1031 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort)
1032 # (BINT or num_str, BINT or num_str) return cond_code
1033
1034 # set up parameters
1035 my ($self,$x,$y) = (ref($_[0]),@_);
1036
1037 # objectify is costly, so avoid it
1038 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1039 {
1040 ($self,$x,$y) = objectify(2,@_);
1041 }
1042
1043 return $upgrade->bcmp($x,$y) if defined $upgrade &&
1044 ((!$x->isa($self)) || (!$y->isa($self)));
1045
1046 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1047 {
1048 # handle +-inf and NaN
1049 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1050 return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
1051 return +1 if $x->{sign} eq '+inf';
1052 return -1 if $x->{sign} eq '-inf';
1053 return -1 if $y->{sign} eq '+inf';
1054 return +1;
1055 }
1056 # check sign for speed first
1057 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y
1058 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0
1059
1060 # have same sign, so compare absolute values. Don't make tests for zero here
1061 # because it's actually slower than testin in Calc (especially w/ Pari et al)
1062
1063 # post-normalized compare for internal use (honors signs)
1064 if ($x->{sign} eq '+')
1065 {
1066 # $x and $y both > 0
1067 return $CALC->_acmp($x->{value},$y->{value});
1068 }
1069
1070 # $x && $y both < 0
1071 $CALC->_acmp($y->{value},$x->{value}); # swaped acmp (lib returns 0,1,-1)
1072 }
1073
1074sub bacmp
1075 {
1076 # Compares 2 values, ignoring their signs.
1077 # Returns one of undef, <0, =0, >0. (suitable for sort)
1078 # (BINT, BINT) return cond_code
1079
1080 # set up parameters
1081 my ($self,$x,$y) = (ref($_[0]),@_);
1082 # objectify is costly, so avoid it
1083 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1084 {
1085 ($self,$x,$y) = objectify(2,@_);
1086 }
1087
1088 return $upgrade->bacmp($x,$y) if defined $upgrade &&
1089 ((!$x->isa($self)) || (!$y->isa($self)));
1090
1091 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1092 {
1093 # handle +-inf and NaN
1094 return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1095 return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
1096 return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/;
1097 return -1;
1098 }
1099 $CALC->_acmp($x->{value},$y->{value}); # lib does only 0,1,-1
1100 }
1101
1102sub badd
1103 {
1104 # add second arg (BINT or string) to first (BINT) (modifies first)
1105 # return result as BINT
1106
1107 # set up parameters
1108 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1109 # objectify is costly, so avoid it
1110 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1111 {
1112 ($self,$x,$y,@r) = objectify(2,@_);
1113 }
1114
1115 return $x if $x->modify('badd');
1116 return $upgrade->badd($upgrade->new($x),$upgrade->new($y),@r) if defined $upgrade &&
1117 ((!$x->isa($self)) || (!$y->isa($self)));
1118
1119 $r[3] = $y; # no push!
1120 # inf and NaN handling
1121 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
1122 {
1123 # NaN first
1124 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1125 # inf handling
1126 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1127 {
1128 # +inf++inf or -inf+-inf => same, rest is NaN
1129 return $x if $x->{sign} eq $y->{sign};
1130 return $x->bnan();
1131 }
1132 # +-inf + something => +inf
1133 # something +-inf => +-inf
1134 $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
1135 return $x;
1136 }
1137
1138 my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
1139
1140 if ($sx eq $sy)
1141 {
1142 $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
1143 }
1144 else
1145 {
1146 my $a = $CALC->_acmp ($y->{value},$x->{value}); # absolute compare
1147 if ($a > 0)
1148 {
1149 $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
1150 $x->{sign} = $sy;
1151 }
1152 elsif ($a == 0)
1153 {
1154 # speedup, if equal, set result to 0
1155 $x->{value} = $CALC->_zero();
1156 $x->{sign} = '+';
1157 }
1158 else # a < 0
1159 {
1160 $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
1161 }
1162 }
1163 $x->round(@r);
1164 }
1165
1166sub bsub
1167 {
1168 # (BINT or num_str, BINT or num_str) return BINT
1169 # subtract second arg from first, modify first
1170
1171 # set up parameters
1172 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1173
1174 # objectify is costly, so avoid it
1175 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1176 {
1177 ($self,$x,$y,@r) = objectify(2,@_);
1178 }
1179
1180 return $x if $x->modify('bsub');
1181
1182 return $upgrade->new($x)->bsub($upgrade->new($y),@r) if defined $upgrade &&
1183 ((!$x->isa($self)) || (!$y->isa($self)));
1184
1185 return $x->round(@r) if $y->is_zero();
1186
1187 # To correctly handle the lone special case $x->bsub($x), we note the sign
1188 # of $x, then flip the sign from $y, and if the sign of $x did change, too,
1189 # then we caught the special case:
1190 my $xsign = $x->{sign};
1191 $y->{sign} =~ tr/+\-/-+/; # does nothing for NaN
1192 if ($xsign ne $x->{sign})
1193 {
1194 # special case of $x->bsub($x) results in 0
1195 return $x->bzero(@r) if $xsign =~ /^[+-]$/;
1196 return $x->bnan(); # NaN, -inf, +inf
1197 }
1198 $x->badd($y,@r); # badd does not leave internal zeros
1199 $y->{sign} =~ tr/+\-/-+/; # refix $y (does nothing for NaN)
1200 $x; # already rounded by badd() or no round nec.
1201 }
1202
1203sub binc
1204 {
1205 # increment arg by one
1206 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1207 return $x if $x->modify('binc');
1208
1209 if ($x->{sign} eq '+')
1210 {
1211 $x->{value} = $CALC->_inc($x->{value});
1212 return $x->round($a,$p,$r);
1213 }
1214 elsif ($x->{sign} eq '-')
1215 {
1216 $x->{value} = $CALC->_dec($x->{value});
1217 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1218 return $x->round($a,$p,$r);
1219 }
1220 # inf, nan handling etc
1221 $x->badd($self->bone(),$a,$p,$r); # badd does round
1222 }
1223
1224sub bdec
1225 {
1226 # decrement arg by one
1227 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1228 return $x if $x->modify('bdec');
1229
1230 if ($x->{sign} eq '-')
1231 {
1232 # x already < 0
1233 $x->{value} = $CALC->_inc($x->{value});
1234 }
1235 else
1236 {
1237 return $x->badd($self->bone('-'),@r) unless $x->{sign} eq '+'; # inf or NaN
1238 # >= 0
1239 if ($CALC->_is_zero($x->{value}))
1240 {
1241 # == 0
1242 $x->{value} = $CALC->_one(); $x->{sign} = '-'; # 0 => -1
1243 }
1244 else
1245 {
1246 # > 0
1247 $x->{value} = $CALC->_dec($x->{value});
1248 }
1249 }
1250 $x->round(@r);
1251 }
1252
1253sub blog
1254 {
1255 # calculate $x = $a ** $base + $b and return $a (e.g. the log() to base
1256 # $base of $x)
1257
1258 # set up parameters
1259 my ($self,$x,$base,@r) = (undef,@_);
1260 # objectify is costly, so avoid it
1261 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1262 {
1263 ($self,$x,$base,@r) = objectify(2,@_);
1264 }
1265
1266 return $x if $x->modify('blog');
1267
1268 $base = $self->new($base) if defined $base && !ref $base;
1269
1270 # inf, -inf, NaN, <0 => NaN
1271 return $x->bnan()
1272 if $x->{sign} ne '+' || (defined $base && $base->{sign} ne '+');
1273
1274 return $upgrade->blog($upgrade->new($x),$base,@r) if
1275 defined $upgrade;
1276
1277 # fix for bug #24969:
1278 # the default base is e (Euler's number) which is not an integer
1279 if (!defined $base)
1280 {
1281 require Math::BigFloat;
1282 my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int();
1283 # modify $x in place
1284 $x->{value} = $u->{value};
1285 $x->{sign} = $u->{sign};
1286 return $x;
1287 }
1288
1289 my ($rc,$exact) = $CALC->_log_int($x->{value},$base->{value});
1290 return $x->bnan() unless defined $rc; # not possible to take log?
1291 $x->{value} = $rc;
1292 $x->round(@r);
1293 }
1294
1295sub bnok
1296 {
1297 # Calculate n over k (binomial coefficient or "choose" function) as integer.
1298 # set up parameters
1299 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1300
1301 # objectify is costly, so avoid it
1302 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1303 {
1304 ($self,$x,$y,@r) = objectify(2,@_);
1305 }
1306
1307 return $x if $x->modify('bnok');
1308 return $x->bnan() if $x->{sign} eq 'NaN' || $y->{sign} eq 'NaN';
1309 return $x->binf() if $x->{sign} eq '+inf';
1310
1311 # k > n or k < 0 => 0
1312 my $cmp = $x->bacmp($y);
1313 return $x->bzero() if $cmp < 0 || $y->{sign} =~ /^-/;
1314 # k == n => 1
1315 return $x->bone(@r) if $cmp == 0;
1316
1317 if ($CALC->can('_nok'))
1318 {
1319 $x->{value} = $CALC->_nok($x->{value},$y->{value});
1320 }
1321 else
1322 {
1323 # ( 7 ) 7! 1*2*3*4 * 5*6*7 5 * 6 * 7 6 7
1324 # ( - ) = --------- = --------------- = --------- = 5 * - * -
1325 # ( 3 ) (7-3)! 3! 1*2*3*4 * 1*2*3 1 * 2 * 3 2 3
1326
1327 if (!$y->is_zero())
1328 {
1329 my $z = $x - $y;
1330 $z->binc();
1331 my $r = $z->copy(); $z->binc();
1332 my $d = $self->new(2);
1333 while ($z->bacmp($x) <= 0) # f <= x ?
1334 {
1335 $r->bmul($z); $r->bdiv($d);
1336 $z->binc(); $d->binc();
1337 }
1338 $x->{value} = $r->{value}; $x->{sign} = '+';
1339 }
1340 else { $x->bone(); }
1341 }
1342 $x->round(@r);
1343 }
1344
1345sub bexp
1346 {
1347 # Calculate e ** $x (Euler's number to the power of X), truncated to
1348 # an integer value.
1349 my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1350 return $x if $x->modify('bexp');
1351
1352 # inf, -inf, NaN, <0 => NaN
1353 return $x->bnan() if $x->{sign} eq 'NaN';
1354 return $x->bone() if $x->is_zero();
1355 return $x if $x->{sign} eq '+inf';
1356 return $x->bzero() if $x->{sign} eq '-inf';
1357
1358 my $u;
1359 {
1360 # run through Math::BigFloat unless told otherwise
1361 require Math::BigFloat unless defined $upgrade;
1362 local $upgrade = 'Math::BigFloat' unless defined $upgrade;
1363 # calculate result, truncate it to integer
1364 $u = $upgrade->bexp($upgrade->new($x),@r);
1365 }
1366
1367 if (!defined $upgrade)
1368 {
1369 $u = $u->as_int();
1370 # modify $x in place
1371 $x->{value} = $u->{value};
1372 $x->round(@r);
1373 }
1374 else { $x = $u; }
1375 }
1376
1377sub blcm
1378 {
1379 # (BINT or num_str, BINT or num_str) return BINT
1380 # does not modify arguments, but returns new object
1381 # Lowest Common Multiple
1382
1383 my $y = shift; my ($x);
1384 if (ref($y))
1385 {
1386 $x = $y->copy();
1387 }
1388 else
1389 {
1390 $x = $class->new($y);
1391 }
1392 my $self = ref($x);
1393 while (@_)
1394 {
1395 my $y = shift; $y = $self->new($y) if !ref ($y);
1396 $x = __lcm($x,$y);
1397 }
1398 $x;
1399 }
1400
1401sub bgcd
1402 {
1403 # (BINT or num_str, BINT or num_str) return BINT
1404 # does not modify arguments, but returns new object
1405 # GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff)
1406
1407 my $y = shift;
1408 $y = $class->new($y) if !ref($y);
1409 my $self = ref($y);
1410 my $x = $y->copy()->babs(); # keep arguments
1411 return $x->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN?
1412
1413 while (@_)
1414 {
1415 $y = shift; $y = $self->new($y) if !ref($y);
1416 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN?
1417 $x->{value} = $CALC->_gcd($x->{value},$y->{value});
1418 last if $CALC->_is_one($x->{value});
1419 }
1420 $x;
1421 }
1422
1423sub bnot
1424 {
1425 # (num_str or BINT) return BINT
1426 # represent ~x as twos-complement number
1427 # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1428 my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1429
1430 return $x if $x->modify('bnot');
1431 $x->binc()->bneg(); # binc already does round
1432 }
1433
1434##############################################################################
1435# is_foo test routines
1436# we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1437
1438sub is_zero
1439
# spent 19µs (12+7) within Math::BigInt::is_zero which was called 2 times, avg 10µs/call: # 2 times (12µs+7µs) by Math::BigInt::blsft at line 2069, avg 10µs/call
{
1440 # return true if arg (BINT or num_str) is zero (array '+', '0')
1441614µs my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1442
144322µs return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't
# spent 2µs making 2 calls to Math::BigInt::CORE:match, avg 950ns/call
144425µs $CALC->_is_zero($x->{value});
# spent 5µs making 2 calls to Math::BigInt::Calc::_is_zero, avg 2µs/call
1445 }
1446
1447sub is_nan
1448 {
1449 # return true if arg (BINT or num_str) is NaN
1450 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1451
1452 $x->{sign} eq $nan ? 1 : 0;
1453 }
1454
1455sub is_inf
1456 {
1457 # return true if arg (BINT or num_str) is +-inf
1458 my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1459
1460 if (defined $sign)
1461 {
1462 $sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf
1463 $sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-'
1464 return $x->{sign} =~ /^$sign$/ ? 1 : 0;
1465 }
1466 $x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity
1467 }
1468
1469sub is_one
1470 {
1471 # return true if arg (BINT or num_str) is +1, or -1 if sign is given
1472 my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1473
1474 $sign = '+' if !defined $sign || $sign ne '-';
1475
1476 return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either
1477 $CALC->_is_one($x->{value});
1478 }
1479
1480sub is_odd
1481 {
1482 # return true when arg (BINT or num_str) is odd, false for even
1483 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1484
1485 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1486 $CALC->_is_odd($x->{value});
1487 }
1488
1489sub is_even
1490 {
1491 # return true when arg (BINT or num_str) is even, false for odd
1492 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1493
1494 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't
1495 $CALC->_is_even($x->{value});
1496 }
1497
1498sub is_positive
1499 {
1500 # return true when arg (BINT or num_str) is positive (> 0)
1501 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1502
1503 return 1 if $x->{sign} eq '+inf'; # +inf is positive
1504
1505 # 0+ is neither positive nor negative
1506 ($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0;
1507 }
1508
1509sub is_negative
1510 {
1511 # return true when arg (BINT or num_str) is negative (< 0)
1512 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1513
1514 $x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not
1515 }
1516
1517sub is_int
1518 {
1519 # return true when arg (BINT or num_str) is an integer
1520 # always true for BigInt, but different for BigFloats
1521 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1522
1523 $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't
1524 }
1525
1526###############################################################################
1527
1528sub bmul
1529 {
1530 # multiply the first number by the second number
1531 # (BINT or num_str, BINT or num_str) return BINT
1532
1533 # set up parameters
1534 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1535 # objectify is costly, so avoid it
1536 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1537 {
1538 ($self,$x,$y,@r) = objectify(2,@_);
1539 }
1540
1541 return $x if $x->modify('bmul');
1542
1543 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1544
1545 # inf handling
1546 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1547 {
1548 return $x->bnan() if $x->is_zero() || $y->is_zero();
1549 # result will always be +-inf:
1550 # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1551 # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1552 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1553 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1554 return $x->binf('-');
1555 }
1556
1557 return $upgrade->bmul($x,$upgrade->new($y),@r)
1558 if defined $upgrade && !$y->isa($self);
1559
1560 $r[3] = $y; # no push here
1561
1562 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1563
1564 $x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
1565 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
1566
1567 $x->round(@r);
1568 }
1569
1570sub bmuladd
1571 {
1572 # multiply two numbers and then add the third to the result
1573 # (BINT or num_str, BINT or num_str, BINT or num_str) return BINT
1574
1575 # set up parameters
1576 my ($self,$x,$y,$z,@r) = objectify(3,@_);
1577
1578 return $x if $x->modify('bmuladd');
1579
1580 return $x->bnan() if ($x->{sign} eq $nan) ||
1581 ($y->{sign} eq $nan) ||
1582 ($z->{sign} eq $nan);
1583
1584 # inf handling of x and y
1585 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1586 {
1587 return $x->bnan() if $x->is_zero() || $y->is_zero();
1588 # result will always be +-inf:
1589 # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1590 # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1591 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
1592 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
1593 return $x->binf('-');
1594 }
1595 # inf handling x*y and z
1596 if (($z->{sign} =~ /^[+-]inf$/))
1597 {
1598 # something +-inf => +-inf
1599 $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/;
1600 }
1601
1602 return $upgrade->bmuladd($x,$upgrade->new($y),$upgrade->new($z),@r)
1603 if defined $upgrade && (!$y->isa($self) || !$z->isa($self) || !$x->isa($self));
1604
1605 # TODO: what if $y and $z have A or P set?
1606 $r[3] = $z; # no push here
1607
1608 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1609
1610 $x->{value} = $CALC->_mul($x->{value},$y->{value}); # do actual math
1611 $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0
1612
1613 my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs
1614
1615 if ($sx eq $sz)
1616 {
1617 $x->{value} = $CALC->_add($x->{value},$z->{value}); # same sign, abs add
1618 }
1619 else
1620 {
1621 my $a = $CALC->_acmp ($z->{value},$x->{value}); # absolute compare
1622 if ($a > 0)
1623 {
1624 $x->{value} = $CALC->_sub($z->{value},$x->{value},1); # abs sub w/ swap
1625 $x->{sign} = $sz;
1626 }
1627 elsif ($a == 0)
1628 {
1629 # speedup, if equal, set result to 0
1630 $x->{value} = $CALC->_zero();
1631 $x->{sign} = '+';
1632 }
1633 else # a < 0
1634 {
1635 $x->{value} = $CALC->_sub($x->{value}, $z->{value}); # abs sub
1636 }
1637 }
1638 $x->round(@r);
1639 }
1640
1641sub _div_inf
1642 {
1643 # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1644 my ($self,$x,$y) = @_;
1645
1646 # NaN if x == NaN or y == NaN or x==y==0
1647 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1648 if (($x->is_nan() || $y->is_nan()) ||
1649 ($x->is_zero() && $y->is_zero()));
1650
1651 # +-inf / +-inf == NaN, remainder also NaN
1652 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1653 {
1654 return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1655 }
1656 # x / +-inf => 0, remainder x (works even if x == 0)
1657 if ($y->{sign} =~ /^[+-]inf$/)
1658 {
1659 my $t = $x->copy(); # bzero clobbers up $x
1660 return wantarray ? ($x->bzero(),$t) : $x->bzero()
1661 }
1662
1663 # 5 / 0 => +inf, -6 / 0 => -inf
1664 # +inf / 0 = inf, inf, and -inf / 0 => -inf, -inf
1665 # exception: -8 / 0 has remainder -8, not 8
1666 # exception: -inf / 0 has remainder -inf, not inf
1667 if ($y->is_zero())
1668 {
1669 # +-inf / 0 => special case for -inf
1670 return wantarray ? ($x,$x->copy()) : $x if $x->is_inf();
1671 if (!$x->is_zero() && !$x->is_inf())
1672 {
1673 my $t = $x->copy(); # binf clobbers up $x
1674 return wantarray ?
1675 ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1676 }
1677 }
1678
1679 # last case: +-inf / ordinary number
1680 my $sign = '+inf';
1681 $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1682 $x->{sign} = $sign;
1683 return wantarray ? ($x,$self->bzero()) : $x;
1684 }
1685
1686sub bdiv
1687 {
1688 # (dividend: BINT or num_str, divisor: BINT or num_str) return
1689 # (BINT,BINT) (quo,rem) or BINT (only rem)
1690
1691 # set up parameters
1692 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1693 # objectify is costly, so avoid it
1694 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1695 {
1696 ($self,$x,$y,@r) = objectify(2,@_);
1697 }
1698
1699 return $x if $x->modify('bdiv');
1700
1701 return $self->_div_inf($x,$y)
1702 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1703
1704 return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1705 if defined $upgrade;
1706
1707 $r[3] = $y; # no push!
1708
1709 # calc new sign and in case $y == +/- 1, return $x
1710 my $xsign = $x->{sign}; # keep
1711 $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+');
1712
1713 if (wantarray)
1714 {
1715 my $rem = $self->bzero();
1716 ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1717 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1718 $rem->{_a} = $x->{_a};
1719 $rem->{_p} = $x->{_p};
1720 $x->round(@r);
1721 if (! $CALC->_is_zero($rem->{value}))
1722 {
1723 $rem->{sign} = $y->{sign};
1724 $rem = $y->copy()->bsub($rem) if $xsign ne $y->{sign}; # one of them '-'
1725 }
1726 else
1727 {
1728 $rem->{sign} = '+'; # dont leave -0
1729 }
1730 $rem->round(@r);
1731 return ($x,$rem);
1732 }
1733
1734 $x->{value} = $CALC->_div($x->{value},$y->{value});
1735 $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1736
1737 $x->round(@r);
1738 }
1739
1740###############################################################################
1741# modulus functions
1742
1743sub bmod
1744 {
1745 # modulus (or remainder)
1746 # (BINT or num_str, BINT or num_str) return BINT
1747
1748 # set up parameters
1749 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1750 # objectify is costly, so avoid it
1751 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1752 {
1753 ($self,$x,$y,@r) = objectify(2,@_);
1754 }
1755
1756 return $x if $x->modify('bmod');
1757 $r[3] = $y; # no push!
1758 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1759 {
1760 my ($d,$r) = $self->_div_inf($x,$y);
1761 $x->{sign} = $r->{sign};
1762 $x->{value} = $r->{value};
1763 return $x->round(@r);
1764 }
1765
1766 # calc new sign and in case $y == +/- 1, return $x
1767 $x->{value} = $CALC->_mod($x->{value},$y->{value});
1768 if (!$CALC->_is_zero($x->{value}))
1769 {
1770 $x->{value} = $CALC->_sub($y->{value},$x->{value},1) # $y-$x
1771 if ($x->{sign} ne $y->{sign});
1772 $x->{sign} = $y->{sign};
1773 }
1774 else
1775 {
1776 $x->{sign} = '+'; # dont leave -0
1777 }
1778 $x->round(@r);
1779 }
1780
1781sub bmodinv
1782 {
1783 # Return modular multiplicative inverse: z is the modular inverse of x (mod
1784 # y) if and only if x*z (mod y) = 1 (mod y). If the modulus y is larger than
1785 # one, x and z are relative primes (i.e., their greatest common divisor is
1786 # one).
1787 #
1788 # If no modular multiplicative inverse exists, NaN is returned.
1789
1790 # set up parameters
1791 my ($self,$x,$y,@r) = (undef,@_);
1792 # objectify is costly, so avoid it
1793 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1794 {
1795 ($self,$x,$y,@r) = objectify(2,@_);
1796 }
1797
1798 return $x if $x->modify('bmodinv');
1799
1800 # Return NaN if one or both arguments is +inf, -inf, or nan.
1801
1802 return $x->bnan() if ($y->{sign} !~ /^[+-]$/ ||
1803 $x->{sign} !~ /^[+-]$/);
1804
1805 # Return NaN if $y is zero; 1 % 0 makes no sense.
1806
1807 return $x->bnan() if $y->is_zero();
1808
1809 # Return 0 in the trivial case. $x % 1 or $x % -1 is zero for all finite
1810 # integers $x.
1811
1812 return $x->bzero() if ($y->is_one() ||
1813 $y->is_one('-'));
1814
1815 # Return NaN if $x = 0, or $x modulo $y is zero. The only valid case when
1816 # $x = 0 is when $y = 1 or $y = -1, but that was covered above.
1817 #
1818 # Note that computing $x modulo $y here affects the value we'll feed to
1819 # $CALC->_modinv() below when $x and $y have opposite signs. E.g., if $x =
1820 # 5 and $y = 7, those two values are fed to _modinv(), but if $x = -5 and
1821 # $y = 7, the values fed to _modinv() are $x = 2 (= -5 % 7) and $y = 7.
1822 # The value if $x is affected only when $x and $y have opposite signs.
1823
1824 $x->bmod($y);
1825 return $x->bnan() if $x->is_zero();
1826
1827 # Compute the modular multiplicative inverse of the absolute values. We'll
1828 # correct for the signs of $x and $y later. Return NaN if no GCD is found.
1829
1830 ($x->{value}, $x->{sign}) = $CALC->_modinv($x->{value}, $y->{value});
1831 return $x->bnan() if !defined $x->{value};
1832
1833 # Library inconsistency workaround: _modinv() in Math::BigInt::GMP versions
1834 # <= 1.32 return undef rather than a "+" for the sign.
1835
1836 $x->{sign} = '+' unless defined $x->{sign};
1837
1838 # When one or both arguments are negative, we have the following
1839 # relations. If x and y are positive:
1840 #
1841 # modinv(-x, -y) = -modinv(x, y)
1842 # modinv(-x, y) = y - modinv(x, y) = -modinv(x, y) (mod y)
1843 # modinv( x, -y) = modinv(x, y) - y = modinv(x, y) (mod -y)
1844
1845 # We must swap the sign of the result if the original $x is negative.
1846 # However, we must compensate for ignoring the signs when computing the
1847 # inverse modulo. The net effect is that we must swap the sign of the
1848 # result if $y is negative.
1849
1850 $x -> bneg() if $y->{sign} eq '-';
1851
1852 # Compute $x modulo $y again after correcting the sign.
1853
1854 $x -> bmod($y) if $x->{sign} ne $y->{sign};
1855
1856 return $x;
1857 }
1858
1859sub bmodpow
1860 {
1861 # Modular exponentiation. Raises a very large number to a very large exponent
1862 # in a given very large modulus quickly, thanks to binary exponentiation.
1863 # Supports negative exponents.
1864 my ($self,$num,$exp,$mod,@r) = objectify(3,@_);
1865
1866 return $num if $num->modify('bmodpow');
1867
1868 # When the exponent 'e' is negative, use the following relation, which is
1869 # based on finding the multiplicative inverse 'd' of 'b' modulo 'm':
1870 #
1871 # b^(-e) (mod m) = d^e (mod m) where b*d = 1 (mod m)
1872
1873 $num->bmodinv($mod) if ($exp->{sign} eq '-');
1874
1875 # Check for valid input. All operands must be finite, and the modulus must be
1876 # non-zero.
1877
1878 return $num->bnan() if ($num->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
1879 $exp->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
1880 $mod->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf
1881 $mod->is_zero());
1882
1883 # Compute 'a (mod m)', ignoring the signs on 'a' and 'm'. If the resulting
1884 # value is zero, the output is also zero, regardless of the signs on 'a' and
1885 # 'm'.
1886
1887 my $value = $CALC->_modpow($num->{value}, $exp->{value}, $mod->{value});
1888 my $sign = '+';
1889
1890 # If the resulting value is non-zero, we have four special cases, depending
1891 # on the signs on 'a' and 'm'.
1892
1893 unless ($CALC->_is_zero($value)) {
1894
1895 # There is a negative sign on 'a' (= $num**$exp) only if the number we
1896 # are exponentiating ($num) is negative and the exponent ($exp) is odd.
1897
1898 if ($num->{sign} eq '-' && $exp->is_odd()) {
1899
1900 # When both the number 'a' and the modulus 'm' have a negative sign,
1901 # use this relation:
1902 #
1903 # -a (mod -m) = -(a (mod m))
1904
1905 if ($mod->{sign} eq '-') {
1906 $sign = '-';
1907 }
1908
1909 # When only the number 'a' has a negative sign, use this relation:
1910 #
1911 # -a (mod m) = m - (a (mod m))
1912
1913 else {
1914 # Use copy of $mod since _sub() modifies the first argument.
1915 my $mod = $CALC->_copy($mod->{value});
1916 $value = $CALC->_sub($mod, $value);
1917 $sign = '+';
1918 }
1919
1920 } else {
1921
1922 # When only the modulus 'm' has a negative sign, use this relation:
1923 #
1924 # a (mod -m) = (a (mod m)) - m
1925 # = -(m - (a (mod m)))
1926
1927 if ($mod->{sign} eq '-') {
1928 # Use copy of $mod since _sub() modifies the first argument.
1929 my $mod = $CALC->_copy($mod->{value});
1930 $value = $CALC->_sub($mod, $value);
1931 $sign = '-';
1932 }
1933
1934 # When neither the number 'a' nor the modulus 'm' have a negative
1935 # sign, directly return the already computed value.
1936 #
1937 # (a (mod m))
1938
1939 }
1940
1941 }
1942
1943 $num->{value} = $value;
1944 $num->{sign} = $sign;
1945
1946 return $num;
1947 }
1948
1949###############################################################################
1950
1951sub bfac
1952 {
1953 # (BINT or num_str, BINT or num_str) return BINT
1954 # compute factorial number from $x, modify $x in place
1955 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1956
1957 return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf
1958 return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN
1959
1960 $x->{value} = $CALC->_fac($x->{value});
1961 $x->round(@r);
1962 }
1963
1964sub bpow
1965 {
1966 # (BINT or num_str, BINT or num_str) return BINT
1967 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1968 # modifies first argument
1969
1970 # set up parameters
1971 my ($self,$x,$y,@r) = (ref($_[0]),@_);
1972 # objectify is costly, so avoid it
1973 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1974 {
1975 ($self,$x,$y,@r) = objectify(2,@_);
1976 }
1977
1978 return $x if $x->modify('bpow');
1979
1980 return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1981
1982 # inf handling
1983 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1984 {
1985 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1986 {
1987 # +-inf ** +-inf
1988 return $x->bnan();
1989 }
1990 # +-inf ** Y
1991 if ($x->{sign} =~ /^[+-]inf/)
1992 {
1993 # +inf ** 0 => NaN
1994 return $x->bnan() if $y->is_zero();
1995 # -inf ** -1 => 1/inf => 0
1996 return $x->bzero() if $y->is_one('-') && $x->is_negative();
1997
1998 # +inf ** Y => inf
1999 return $x if $x->{sign} eq '+inf';
2000
2001 # -inf ** Y => -inf if Y is odd
2002 return $x if $y->is_odd();
2003 return $x->babs();
2004 }
2005 # X ** +-inf
2006
2007 # 1 ** +inf => 1
2008 return $x if $x->is_one();
2009
2010 # 0 ** inf => 0
2011 return $x if $x->is_zero() && $y->{sign} =~ /^[+]/;
2012
2013 # 0 ** -inf => inf
2014 return $x->binf() if $x->is_zero();
2015
2016 # -1 ** -inf => NaN
2017 return $x->bnan() if $x->is_one('-') && $y->{sign} =~ /^[-]/;
2018
2019 # -X ** -inf => 0
2020 return $x->bzero() if $x->{sign} eq '-' && $y->{sign} =~ /^[-]/;
2021
2022 # -1 ** inf => NaN
2023 return $x->bnan() if $x->{sign} eq '-';
2024
2025 # X ** inf => inf
2026 return $x->binf() if $y->{sign} =~ /^[+]/;
2027 # X ** -inf => 0
2028 return $x->bzero();
2029 }
2030
2031 return $upgrade->bpow($upgrade->new($x),$y,@r)
2032 if defined $upgrade && (!$y->isa($self) || $y->{sign} eq '-');
2033
2034 $r[3] = $y; # no push!
2035
2036 # cases 0 ** Y, X ** 0, X ** 1, 1 ** Y are handled by Calc or Emu
2037
2038 my $new_sign = '+';
2039 $new_sign = $y->is_odd() ? '-' : '+' if ($x->{sign} ne '+');
2040
2041 # 0 ** -7 => ( 1 / (0 ** 7)) => 1 / 0 => +inf
2042 return $x->binf()
2043 if $y->{sign} eq '-' && $x->{sign} eq '+' && $CALC->_is_zero($x->{value});
2044 # 1 ** -y => 1 / (1 ** |y|)
2045 # so do test for negative $y after above's clause
2046 return $x->bnan() if $y->{sign} eq '-' && !$CALC->_is_one($x->{value});
2047
2048 $x->{value} = $CALC->_pow($x->{value},$y->{value});
2049 $x->{sign} = $new_sign;
2050 $x->{sign} = '+' if $CALC->_is_zero($y->{value});
2051 $x->round(@r);
2052 }
2053
2054sub blsft
2055
# spent 218µs (36+181) within Math::BigInt::blsft which was called 2 times, avg 109µs/call: # 2 times (36µs+181µs) by Math::BigInt::__ANON__[/usr/share/perl/5.14/Math/BigInt.pm:121] at line 120, avg 109µs/call
{
2056 # (BINT or num_str, BINT or num_str) return BINT
2057 # compute x << y, base n, y >= 0
2058
2059 # set up parameters
20601839µs my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
2061 # objectify is costly, so avoid it
2062 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
2063 {
2064 ($self,$x,$y,$n,@r) = objectify(2,@_);
2065 }
2066
206721µs return $x if $x->modify('blsft');
# spent 1µs making 2 calls to Math::BigInt::modify, avg 550ns/call
206843µs return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
# spent 3µs making 4 calls to Math::BigInt::CORE:match, avg 725ns/call
2069219µs return $x->round(@r) if $y->is_zero();
# spent 19µs making 2 calls to Math::BigInt::is_zero, avg 10µs/call
2070
2071 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
2072
20732141µs $x->{value} = $CALC->_lsft($x->{value},$y->{value},$n);
# spent 141µs making 2 calls to Math::BigInt::Calc::_lsft, avg 71µs/call
2074217µs $x->round(@r);
# spent 17µs making 2 calls to Math::BigInt::round, avg 8µs/call
2075 }
2076
2077sub brsft
2078 {
2079 # (BINT or num_str, BINT or num_str) return BINT
2080 # compute x >> y, base n, y >= 0
2081
2082 # set up parameters
2083 my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
2084 # objectify is costly, so avoid it
2085 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
2086 {
2087 ($self,$x,$y,$n,@r) = objectify(2,@_);
2088 }
2089
2090 return $x if $x->modify('brsft');
2091 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
2092 return $x->round(@r) if $y->is_zero();
2093 return $x->bzero(@r) if $x->is_zero(); # 0 => 0
2094
2095 $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
2096
2097 # this only works for negative numbers when shifting in base 2
2098 if (($x->{sign} eq '-') && ($n == 2))
2099 {
2100 return $x->round(@r) if $x->is_one('-'); # -1 => -1
2101 if (!$y->is_one())
2102 {
2103 # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
2104 # but perhaps there is a better emulation for two's complement shift...
2105 # if $y != 1, we must simulate it by doing:
2106 # convert to bin, flip all bits, shift, and be done
2107 $x->binc(); # -3 => -2
2108 my $bin = $x->as_bin();
2109 $bin =~ s/^-0b//; # strip '-0b' prefix
2110 $bin =~ tr/10/01/; # flip bits
2111 # now shift
2112 if ($y >= CORE::length($bin))
2113 {
2114 $bin = '0'; # shifting to far right creates -1
2115 # 0, because later increment makes
2116 # that 1, attached '-' makes it '-1'
2117 # because -1 >> x == -1 !
2118 }
2119 else
2120 {
2121 $bin =~ s/.{$y}$//; # cut off at the right side
2122 $bin = '1' . $bin; # extend left side by one dummy '1'
2123 $bin =~ tr/10/01/; # flip bits back
2124 }
2125 my $res = $self->new('0b'.$bin); # add prefix and convert back
2126 $res->binc(); # remember to increment
2127 $x->{value} = $res->{value}; # take over value
2128 return $x->round(@r); # we are done now, magic, isn't?
2129 }
2130 # x < 0, n == 2, y == 1
2131 $x->bdec(); # n == 2, but $y == 1: this fixes it
2132 }
2133
2134 $x->{value} = $CALC->_rsft($x->{value},$y->{value},$n);
2135 $x->round(@r);
2136 }
2137
2138sub band
2139 {
2140 #(BINT or num_str, BINT or num_str) return BINT
2141 # compute x & y
2142
2143 # set up parameters
2144 my ($self,$x,$y,@r) = (ref($_[0]),@_);
2145 # objectify is costly, so avoid it
2146 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
2147 {
2148 ($self,$x,$y,@r) = objectify(2,@_);
2149 }
2150
2151 return $x if $x->modify('band');
2152
2153 $r[3] = $y; # no push!
2154
2155 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
2156
2157 my $sx = $x->{sign} eq '+' ? 1 : -1;
2158 my $sy = $y->{sign} eq '+' ? 1 : -1;
2159
2160 if ($sx == 1 && $sy == 1)
2161 {
2162 $x->{value} = $CALC->_and($x->{value},$y->{value});
2163 return $x->round(@r);
2164 }
2165
2166 if ($CAN{signed_and})
2167 {
2168 $x->{value} = $CALC->_signed_and($x->{value},$y->{value},$sx,$sy);
2169 return $x->round(@r);
2170 }
2171
2172 require $EMU_LIB;
2173 __emu_band($self,$x,$y,$sx,$sy,@r);
2174 }
2175
2176sub bior
2177 {
2178 #(BINT or num_str, BINT or num_str) return BINT
2179 # compute x | y
2180
2181 # set up parameters
2182 my ($self,$x,$y,@r) = (ref($_[0]),@_);
2183 # objectify is costly, so avoid it
2184 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
2185 {
2186 ($self,$x,$y,@r) = objectify(2,@_);
2187 }
2188
2189 return $x if $x->modify('bior');
2190 $r[3] = $y; # no push!
2191
2192 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
2193
2194 my $sx = $x->{sign} eq '+' ? 1 : -1;
2195 my $sy = $y->{sign} eq '+' ? 1 : -1;
2196
2197 # the sign of X follows the sign of X, e.g. sign of Y irrelevant for bior()
2198
2199 # don't use lib for negative values
2200 if ($sx == 1 && $sy == 1)
2201 {
2202 $x->{value} = $CALC->_or($x->{value},$y->{value});
2203 return $x->round(@r);
2204 }
2205
2206 # if lib can do negative values, let it handle this
2207 if ($CAN{signed_or})
2208 {
2209 $x->{value} = $CALC->_signed_or($x->{value},$y->{value},$sx,$sy);
2210 return $x->round(@r);
2211 }
2212
2213 require $EMU_LIB;
2214 __emu_bior($self,$x,$y,$sx,$sy,@r);
2215 }
2216
2217sub bxor
2218 {
2219 #(BINT or num_str, BINT or num_str) return BINT
2220 # compute x ^ y
2221
2222 # set up parameters
2223 my ($self,$x,$y,@r) = (ref($_[0]),@_);
2224 # objectify is costly, so avoid it
2225 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
2226 {
2227 ($self,$x,$y,@r) = objectify(2,@_);
2228 }
2229
2230 return $x if $x->modify('bxor');
2231 $r[3] = $y; # no push!
2232
2233 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
2234
2235 my $sx = $x->{sign} eq '+' ? 1 : -1;
2236 my $sy = $y->{sign} eq '+' ? 1 : -1;
2237
2238 # don't use lib for negative values
2239 if ($sx == 1 && $sy == 1)
2240 {
2241 $x->{value} = $CALC->_xor($x->{value},$y->{value});
2242 return $x->round(@r);
2243 }
2244
2245 # if lib can do negative values, let it handle this
2246 if ($CAN{signed_xor})
2247 {
2248 $x->{value} = $CALC->_signed_xor($x->{value},$y->{value},$sx,$sy);
2249 return $x->round(@r);
2250 }
2251
2252 require $EMU_LIB;
2253 __emu_bxor($self,$x,$y,$sx,$sy,@r);
2254 }
2255
2256sub length
2257 {
2258 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
2259
2260 my $e = $CALC->_len($x->{value});
2261 wantarray ? ($e,0) : $e;
2262 }
2263
2264sub digit
2265 {
2266 # return the nth decimal digit, negative values count backward, 0 is right
2267 my ($self,$x,$n) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
2268
2269 $n = $n->numify() if ref($n);
2270 $CALC->_digit($x->{value},$n||0);
2271 }
2272
2273sub _trailing_zeros
2274 {
2275 # return the amount of trailing zeros in $x (as scalar)
2276 my $x = shift;
2277 $x = $class->new($x) unless ref $x;
2278
2279 return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc
2280
2281 $CALC->_zeros($x->{value}); # must handle odd values, 0 etc
2282 }
2283
2284sub bsqrt
2285 {
2286 # calculate square root of $x
2287 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
2288
2289 return $x if $x->modify('bsqrt');
2290
2291 return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN
2292 return $x if $x->{sign} eq '+inf'; # sqrt(+inf) == inf
2293
2294 return $upgrade->bsqrt($x,@r) if defined $upgrade;
2295
2296 $x->{value} = $CALC->_sqrt($x->{value});
2297 $x->round(@r);
2298 }
2299
2300sub broot
2301 {
2302 # calculate $y'th root of $x
2303
2304 # set up parameters
2305 my ($self,$x,$y,@r) = (ref($_[0]),@_);
2306
2307 $y = $self->new(2) unless defined $y;
2308
2309 # objectify is costly, so avoid it
2310 if ((!ref($x)) || (ref($x) ne ref($y)))
2311 {
2312 ($self,$x,$y,@r) = objectify(2,$self || $class,@_);
2313 }
2314
2315 return $x if $x->modify('broot');
2316
2317 # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
2318 return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
2319 $y->{sign} !~ /^\+$/;
2320
2321 return $x->round(@r)
2322 if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();
2323
2324 return $upgrade->new($x)->broot($upgrade->new($y),@r) if defined $upgrade;
2325
2326 $x->{value} = $CALC->_root($x->{value},$y->{value});
2327 $x->round(@r);
2328 }
2329
2330sub exponent
2331 {
2332 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
2333 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2334
2335 if ($x->{sign} !~ /^[+-]$/)
2336 {
2337 my $s = $x->{sign}; $s =~ s/^[+-]//; # NaN, -inf,+inf => NaN or inf
2338 return $self->new($s);
2339 }
2340 return $self->bone() if $x->is_zero();
2341
2342 # 12300 => 2 trailing zeros => exponent is 2
2343 $self->new( $CALC->_zeros($x->{value}) );
2344 }
2345
2346sub mantissa
2347 {
2348 # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
2349 my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2350
2351 if ($x->{sign} !~ /^[+-]$/)
2352 {
2353 # for NaN, +inf, -inf: keep the sign
2354 return $self->new($x->{sign});
2355 }
2356 my $m = $x->copy(); delete $m->{_p}; delete $m->{_a};
2357
2358 # that's a bit inefficient:
2359 my $zeros = $CALC->_zeros($m->{value});
2360 $m->brsft($zeros,10) if $zeros != 0;
2361 $m;
2362 }
2363
2364sub parts
2365 {
2366 # return a copy of both the exponent and the mantissa
2367 my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
2368
2369 ($x->mantissa(),$x->exponent());
2370 }
2371
2372##############################################################################
2373# rounding functions
2374
2375sub bfround
2376 {
2377 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
2378 # $n == 0 || $n == 1 => round to integer
2379 my $x = shift; my $self = ref($x) || $x; $x = $self->new($x) unless ref $x;
2380
2381 my ($scale,$mode) = $x->_scale_p(@_);
2382
2383 return $x if !defined $scale || $x->modify('bfround'); # no-op
2384
2385 # no-op for BigInts if $n <= 0
2386 $x->bround( $x->length()-$scale, $mode) if $scale > 0;
2387
2388 delete $x->{_a}; # delete to save memory
2389 $x->{_p} = $scale; # store new _p
2390 $x;
2391 }
2392
2393sub _scan_for_nonzero
2394 {
2395 # internal, used by bround() to scan for non-zeros after a '5'
2396 my ($x,$pad,$xs,$len) = @_;
2397
2398 return 0 if $len == 1; # "5" is trailed by invisible zeros
2399 my $follow = $pad - 1;
2400 return 0 if $follow > $len || $follow < 1;
2401
2402 # use the string form to check whether only '0's follow or not
2403 substr ($xs,-$follow) =~ /[^0]/ ? 1 : 0;
2404 }
2405
2406sub fround
2407 {
2408 # Exists to make life easier for switch between MBF and MBI (should we
2409 # autoload fxxx() like MBF does for bxxx()?)
2410 my $x = shift; $x = $class->new($x) unless ref $x;
2411 $x->bround(@_);
2412 }
2413
2414sub bround
2415 {
2416 # accuracy: +$n preserve $n digits from left,
2417 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
2418 # no-op for $n == 0
2419 # and overwrite the rest with 0's, return normalized number
2420 # do not return $x->bnorm(), but $x
2421
2422 my $x = shift; $x = $class->new($x) unless ref $x;
2423 my ($scale,$mode) = $x->_scale_a(@_);
2424 return $x if !defined $scale || $x->modify('bround'); # no-op
2425
2426 if ($x->is_zero() || $scale == 0)
2427 {
2428 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2429 return $x;
2430 }
2431 return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN
2432
2433 # we have fewer digits than we want to scale to
2434 my $len = $x->length();
2435 # convert $scale to a scalar in case it is an object (put's a limit on the
2436 # number length, but this would already limited by memory constraints), makes
2437 # it faster
2438 $scale = $scale->numify() if ref ($scale);
2439
2440 # scale < 0, but > -len (not >=!)
2441 if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
2442 {
2443 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2444 return $x;
2445 }
2446
2447 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
2448 my ($pad,$digit_round,$digit_after);
2449 $pad = $len - $scale;
2450 $pad = abs($scale-1) if $scale < 0;
2451
2452 # do not use digit(), it is very costly for binary => decimal
2453 # getting the entire string is also costly, but we need to do it only once
2454 my $xs = $CALC->_str($x->{value});
2455 my $pl = -$pad-1;
2456
2457 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
2458 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3
2459 $digit_round = '0'; $digit_round = substr($xs,$pl,1) if $pad <= $len;
2460 $pl++; $pl ++ if $pad >= $len;
2461 $digit_after = '0'; $digit_after = substr($xs,$pl,1) if $pad > 0;
2462
2463 # in case of 01234 we round down, for 6789 up, and only in case 5 we look
2464 # closer at the remaining digits of the original $x, remember decision
2465 my $round_up = 1; # default round up
2466 $round_up -- if
2467 ($mode eq 'trunc') || # trunc by round down
2468 ($digit_after =~ /[01234]/) || # round down anyway,
2469 # 6789 => round up
2470 ($digit_after eq '5') && # not 5000...0000
2471 ($x->_scan_for_nonzero($pad,$xs,$len) == 0) &&
2472 (
2473 ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
2474 ($mode eq 'odd') && ($digit_round =~ /[13579]/) ||
2475 ($mode eq '+inf') && ($x->{sign} eq '-') ||
2476 ($mode eq '-inf') && ($x->{sign} eq '+') ||
2477 ($mode eq 'zero') # round down if zero, sign adjusted below
2478 );
2479 my $put_back = 0; # not yet modified
2480
2481 if (($pad > 0) && ($pad <= $len))
2482 {
2483 substr($xs,-$pad,$pad) = '0' x $pad; # replace with '00...'
2484 $put_back = 1; # need to put back
2485 }
2486 elsif ($pad > $len)
2487 {
2488 $x->bzero(); # round to '0'
2489 }
2490
2491 if ($round_up) # what gave test above?
2492 {
2493 $put_back = 1; # need to put back
2494 $pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0
2495
2496 # we modify directly the string variant instead of creating a number and
2497 # adding it, since that is faster (we already have the string)
2498 my $c = 0; $pad ++; # for $pad == $len case
2499 while ($pad <= $len)
2500 {
2501 $c = substr($xs,-$pad,1) + 1; $c = '0' if $c eq '10';
2502 substr($xs,-$pad,1) = $c; $pad++;
2503 last if $c != 0; # no overflow => early out
2504 }
2505 $xs = '1'.$xs if $c == 0;
2506
2507 }
2508 $x->{value} = $CALC->_new($xs) if $put_back == 1; # put back, if needed
2509
2510 $x->{_a} = $scale if $scale >= 0;
2511 if ($scale < 0)
2512 {
2513 $x->{_a} = $len+$scale;
2514 $x->{_a} = 0 if $scale < -$len;
2515 }
2516 $x;
2517 }
2518
2519sub bfloor
2520 {
2521 # return integer less or equal then number; no-op since it's already integer
2522 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
2523
2524 $x->round(@r);
2525 }
2526
2527sub bceil
2528 {
2529 # return integer greater or equal then number; no-op since it's already int
2530 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
2531
2532 $x->round(@r);
2533 }
2534
2535sub as_number
2536 {
2537 # An object might be asked to return itself as bigint on certain overloaded
2538 # operations. This does exactly this, so that sub classes can simple inherit
2539 # it or override with their own integer conversion routine.
2540 $_[0]->copy();
2541 }
2542
2543sub as_hex
2544 {
2545 # return as hex string, with prefixed 0x
2546 my $x = shift; $x = $class->new($x) if !ref($x);
2547
2548 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2549
2550 my $s = '';
2551 $s = $x->{sign} if $x->{sign} eq '-';
2552 $s . $CALC->_as_hex($x->{value});
2553 }
2554
2555sub as_bin
2556 {
2557 # return as binary string, with prefixed 0b
2558 my $x = shift; $x = $class->new($x) if !ref($x);
2559
2560 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2561
2562 my $s = ''; $s = $x->{sign} if $x->{sign} eq '-';
2563 return $s . $CALC->_as_bin($x->{value});
2564 }
2565
2566sub as_oct
2567 {
2568 # return as octal string, with prefixed 0
2569 my $x = shift; $x = $class->new($x) if !ref($x);
2570
2571 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc
2572
2573 my $s = ''; $s = $x->{sign} if $x->{sign} eq '-';
2574 return $s . $CALC->_as_oct($x->{value});
2575 }
2576
2577##############################################################################
2578# private stuff (internal use only)
2579
2580sub objectify
2581 {
2582 # check for strings, if yes, return objects instead
2583
2584 # the first argument is number of args objectify() should look at it will
2585 # return $count+1 elements, the first will be a classname. This is because
2586 # overloaded '""' calls bstr($object,undef,undef) and this would result in
2587 # useless objects being created and thrown away. So we cannot simple loop
2588 # over @_. If the given count is 0, all arguments will be used.
2589
2590 # If the second arg is a ref, use it as class.
2591 # If not, try to use it as classname, unless undef, then use $class
2592 # (aka Math::BigInt). The latter shouldn't happen,though.
2593
2594 # caller: gives us:
2595 # $x->badd(1); => ref x, scalar y
2596 # Class->badd(1,2); => classname x (scalar), scalar x, scalar y
2597 # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
2598 # Math::BigInt::badd(1,2); => scalar x, scalar y
2599 # In the last case we check number of arguments to turn it silently into
2600 # $class,1,2. (We can not take '1' as class ;o)
2601 # badd($class,1) is not supported (it should, eventually, try to add undef)
2602 # currently it tries 'Math::BigInt' + 1, which will not work.
2603
2604 # some shortcut for the common cases
2605 # $x->unary_op();
2606 return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
2607
2608 my $count = abs(shift || 0);
2609
2610 my (@a,$k,$d); # resulting array, temp, and downgrade
2611 if (ref $_[0])
2612 {
2613 # okay, got object as first
2614 $a[0] = ref $_[0];
2615 }
2616 else
2617 {
2618 # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
2619 $a[0] = $class;
2620 $a[0] = shift if $_[0] =~ /^[A-Z].*::/; # classname as first?
2621 }
2622
262323.95ms276µs
# spent 50µs (24+26) within Math::BigInt::BEGIN@2623 which was called: # once (24µs+26µs) by bigint::import at line 2623
no strict 'refs';
# spent 50µs making 1 call to Math::BigInt::BEGIN@2623 # spent 26µs making 1 call to strict::unimport
2624 # disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
2625 if (defined ${"$a[0]::downgrade"})
2626 {
2627 $d = ${"$a[0]::downgrade"};
2628 ${"$a[0]::downgrade"} = undef;
2629 }
2630
2631 my $up = ${"$a[0]::upgrade"};
2632 # print STDERR "# Now in objectify, my class is today $a[0], count = $count\n";
2633 if ($count == 0)
2634 {
2635 while (@_)
2636 {
2637 $k = shift;
2638 if (!ref($k))
2639 {
2640 $k = $a[0]->new($k);
2641 }
2642 elsif (!defined $up && ref($k) ne $a[0])
2643 {
2644 # foreign object, try to convert to integer
2645 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2646 }
2647 push @a,$k;
2648 }
2649 }
2650 else
2651 {
2652 while ($count > 0)
2653 {
2654 $count--;
2655 $k = shift;
2656 if (!ref($k))
2657 {
2658 $k = $a[0]->new($k);
2659 }
2660 elsif (ref($k) ne $a[0] and !defined $up || ref $k ne $up)
2661 {
2662 # foreign object, try to convert to integer
2663 $k->can('as_number') ? $k = $k->as_number() : $k = $a[0]->new($k);
2664 }
2665 push @a,$k;
2666 }
2667 push @a,@_; # return other params, too
2668 }
2669 if (! wantarray)
2670 {
2671 require Carp; Carp::croak ("$class objectify needs list context");
2672 }
2673 ${"$a[0]::downgrade"} = $d;
2674 @a;
2675 }
2676
2677sub _register_callback
2678 {
2679 my ($class,$callback) = @_;
2680
2681 if (ref($callback) ne 'CODE')
2682 {
2683 require Carp;
2684 Carp::croak ("$callback is not a coderef");
2685 }
2686 $CALLBACKS{$class} = $callback;
2687 }
2688
2689sub import
2690
# spent 24.7ms (2.21+22.5) within Math::BigInt::import which was called 9 times, avg 2.75ms/call: # 9 times (2.21ms+22.5ms) by bigint::import at line 247 of bigint.pm, avg 2.75ms/call
{
2691144156µs my $self = shift;
2692
2693 $IMPORT++; # remember we did import()
2694 my @a; my $l = scalar @_;
2695 my $warn_or_die = 0; # 0 - no warn, 1 - warn, 2 - die
269698µs for ( my $i = 0; $i < $l ; $i++ )
2697 {
2698955µs if ($_[$i] eq ':constant')
2699 {
2700 # this causes overlord er load to step in
2701 overload::constant
2702837µs8396µs
# spent 448µs (52+396) within Math::BigInt::__ANON__[/usr/share/perl/5.14/Math/BigInt.pm:2702] which was called 8 times, avg 56µs/call: # once (25µs+117µs) by main::BEGIN@7 at line 1231 of Value/Convertor.pm # once (4µs+45µs) by main::BEGIN@7 at line 1751 of Value/Convertor.pm # once (4µs+44µs) by main::BEGIN@7 at line 1722 of Value/Convertor.pm # once (4µs+44µs) by main::BEGIN@7 at line 2072 of Value/Convertor.pm # once (4µs+43µs) by main::BEGIN@7 at line 2051 of Value/Convertor.pm # once (4µs+43µs) by main::BEGIN@7 at line 1806 of Value/Convertor.pm # once (4µs+42µs) by main::BEGIN@7 at line 1776 of Value/Convertor.pm # once (3µs+19µs) by main::BEGIN@7 at line 1777 of Value/Convertor.pm
integer => sub { $self->new(shift) },
# spent 396µs making 8 calls to Math::BigInt::new, avg 50µs/call
27039308µs binary => sub { $self->new(shift) };
# spent 308µs making 9 calls to overload::constant, avg 34µs/call
2704 }
2705 elsif ($_[$i] eq 'upgrade')
2706 {
2707 # this causes upgrading
2708 $upgrade = $_[$i+1]; # or undef to disable
2709 $i++;
2710 }
2711 elsif ($_[$i] =~ /^(lib|try|only)\z/)
2712 {
2713 # this causes a different low lib to take care...
2714 $CALC = $_[$i+1] || '';
2715 # lib => 1 (warn on fallback), try => 0 (no warn), only => 2 (die on fallback)
2716 $warn_or_die = 1 if $_[$i] eq 'lib';
2717 $warn_or_die = 2 if $_[$i] eq 'only';
2718 $i++;
2719 }
2720 else
2721 {
2722 push @a, $_[$i];
2723 }
2724 }
2725 # any non :constant stuff is handled by our parent, Exporter
2726 if (@a > 0)
2727 {
2728 require Exporter;
2729
2730 $self->SUPER::import(@a); # need it for subclasses
2731 $self->export_to_level(1,$self,@a); # need it for MBF
2732 }
2733
2734 # try to load core math lib
2735 my @c = split /\s*,\s*/,$CALC;
2736 foreach (@c)
2737 {
2738917µs $_ =~ tr/a-zA-Z0-9://cd; # limit to sane characters
2739 }
2740 push @c, \'Calc' # if all fail, try these
2741 if $warn_or_die < 2; # but not for "only"
2742 $CALC = ''; # signal error
2743 foreach my $l (@c)
2744 {
2745 # fallback libraries are "marked" as \'string', extract string if nec.
27466396µs my $lib = $l; $lib = $$l if ref($l);
2747
2748 next if ($lib || '') eq '';
2749914µs $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
# spent 14µs making 9 calls to Math::BigInt::CORE:match, avg 2µs/call
275096µs $lib =~ s/\.pm$//;
# spent 6µs making 9 calls to Math::BigInt::CORE:subst, avg 689ns/call
27519597µs if ($] < 5.006)
2752 {
2753 # Perl < 5.6.0 dies with "out of memory!" when eval("") and ':constant' is
2754 # used in the same script, or eval("") inside import().
2755 my @parts = split /::/, $lib; # Math::BigInt => Math BigInt
2756 my $file = pop @parts; $file .= '.pm'; # BigInt => BigInt.pm
2757 require File::Spec;
2758 $file = File::Spec->catfile (@parts, $file);
2759 eval { require "$file"; $lib->import( @c ); }
2760 }
2761 else
2762 {
2763 eval "use $lib qw/@c/;";
# spent 352µs executing statements in 9 string evals (merged)
# includes 20.6ms spent executing 9 calls to 9 subs defined therein.
2764 }
276527123µs if ($@ eq '')
2766 {
2767 my $ok = 1;
2768 # loaded it ok, see if the api_version() is high enough
27691818µs1837µs if ($lib->can('api_version') && $lib->api_version() >= 1.0)
# spent 30µs making 9 calls to UNIVERSAL::can, avg 3µs/call # spent 7µs making 9 calls to Math::BigInt::Calc::api_version, avg 800ns/call
2770 {
2771 $ok = 0;
2772 # api_version matches, check if it really provides anything we need
2773 for my $method (qw/
2774 one two ten
2775 str num
2776 add mul div sub dec inc
2777 acmp len digit is_one is_zero is_even is_odd
2778 is_two is_ten
2779 zeros new copy check
2780 from_hex from_oct from_bin as_hex as_bin as_oct
2781 rsft lsft xor and or
2782 mod sqrt root fac pow modinv modpow log_int gcd
2783 /)
2784 {
27853961.50ms396505µs if (!$lib->can("_$method"))
# spent 505µs making 396 calls to UNIVERSAL::can, avg 1µs/call
2786 {
2787 if (($WARN{$lib}||0) < 2)
2788 {
2789 require Carp;
2790 Carp::carp ("$lib is missing method '_$method'");
2791 $WARN{$lib} = 1; # still warn about the lib
2792 }
2793 $ok++; last;
2794 }
2795 }
2796 }
27972719µs if ($ok == 0)
2798 {
2799 $CALC = $lib;
2800 if ($warn_or_die > 0 && ref($l))
2801 {
2802 require Carp;
2803 my $msg = "Math::BigInt: couldn't load specified math lib(s), fallback to $lib";
2804 Carp::carp ($msg) if $warn_or_die == 1;
2805 Carp::croak ($msg) if $warn_or_die == 2;
2806 }
2807 last; # found a usable one, break
2808 }
2809 else
2810 {
2811 if (($WARN{$lib}||0) < 2)
2812 {
2813 my $ver = eval "\$$lib\::VERSION" || 'unknown';
2814 require Carp;
2815 Carp::carp ("Cannot load outdated $lib v$ver, please upgrade");
2816 $WARN{$lib} = 2; # never warn again
2817 }
2818 }
2819 }
2820 }
2821 if ($CALC eq '')
2822 {
2823 require Carp;
2824 if ($warn_or_die == 2)
2825 {
2826 Carp::croak ("Couldn't load specified math lib(s) and fallback disallowed");
2827 }
2828 else
2829 {
2830 Carp::croak ("Couldn't load any math lib(s), not even fallback to Calc.pm");
2831 }
2832 }
2833
2834 # notify callbacks
2835 foreach my $class (keys %CALLBACKS)
2836 {
2837 &{$CALLBACKS{$class}}($CALC);
2838 }
2839
2840 # Fill $CAN with the results of $CALC->can(...) for emulating lower math lib
2841 # functions
2842
2843 %CAN = ();
2844 for my $method (qw/ signed_and signed_or signed_xor /)
2845 {
284627146µs2754µs $CAN{$method} = $CALC->can("_$method") ? 1 : 0;
# spent 54µs making 27 calls to UNIVERSAL::can, avg 2µs/call
2847 }
2848
2849 # import done
2850 }
2851
2852sub from_hex {
2853 # Create a bigint from a hexadecimal string.
2854
2855 my ($self, $str) = @_;
2856
2857 if ($str =~ s/
2858 ^
2859 ( [+-]? )
2860 (0?x)?
2861 (
2862 [0-9a-fA-F]*
2863 ( _ [0-9a-fA-F]+ )*
2864 )
2865 $
2866 //x)
2867 {
2868 # Get a "clean" version of the string, i.e., non-emtpy and with no
2869 # underscores or invalid characters.
2870
2871 my $sign = $1;
2872 my $chrs = $3;
2873 $chrs =~ tr/_//d;
2874 $chrs = '0' unless CORE::length $chrs;
2875
2876 # Initialize output.
2877
2878 my $x = Math::BigInt->bzero();
2879
2880 # The library method requires a prefix.
2881
2882 $x->{value} = $CALC->_from_hex('0x' . $chrs);
2883
2884 # Place the sign.
2885
2886 if ($sign eq '-' && ! $CALC->_is_zero($x->{value})) {
2887 $x->{sign} = '-';
2888 }
2889
2890 return $x;
2891 }
2892
2893 # CORE::hex() parses as much as it can, and ignores any trailing garbage.
2894 # For backwards compatibility, we return NaN.
2895
2896 return $self->bnan();
2897}
2898
2899sub from_oct {
2900 # Create a bigint from an octal string.
2901
2902 my ($self, $str) = @_;
2903
2904 if ($str =~ s/
2905 ^
2906 ( [+-]? )
2907 (
2908 [0-7]*
2909 ( _ [0-7]+ )*
2910 )
2911 $
2912 //x)
2913 {
2914 # Get a "clean" version of the string, i.e., non-emtpy and with no
2915 # underscores or invalid characters.
2916
2917 my $sign = $1;
2918 my $chrs = $2;
2919 $chrs =~ tr/_//d;
2920 $chrs = '0' unless CORE::length $chrs;
2921
2922 # Initialize output.
2923
2924 my $x = Math::BigInt->bzero();
2925
2926 # The library method requires a prefix.
2927
2928 $x->{value} = $CALC->_from_oct('0' . $chrs);
2929
2930 # Place the sign.
2931
2932 if ($sign eq '-' && ! $CALC->_is_zero($x->{value})) {
2933 $x->{sign} = '-';
2934 }
2935
2936 return $x;
2937 }
2938
2939 # CORE::oct() parses as much as it can, and ignores any trailing garbage.
2940 # For backwards compatibility, we return NaN.
2941
2942 return $self->bnan();
2943}
2944
2945sub from_bin {
2946 # Create a bigint from a binary string.
2947
2948 my ($self, $str) = @_;
2949
2950 if ($str =~ s/
2951 ^
2952 ( [+-]? )
2953 (0?b)?
2954 (
2955 [01]*
2956 ( _ [01]+ )*
2957 )
2958 $
2959 //x)
2960 {
2961 # Get a "clean" version of the string, i.e., non-emtpy and with no
2962 # underscores or invalid characters.
2963
2964 my $sign = $1;
2965 my $chrs = $3;
2966 $chrs =~ tr/_//d;
2967 $chrs = '0' unless CORE::length $chrs;
2968
2969 # Initialize output.
2970
2971 my $x = Math::BigInt->bzero();
2972
2973 # The library method requires a prefix.
2974
2975 $x->{value} = $CALC->_from_bin('0b' . $chrs);
2976
2977 # Place the sign.
2978
2979 if ($sign eq '-' && ! $CALC->_is_zero($x->{value})) {
2980 $x->{sign} = '-';
2981 }
2982
2983 return $x;
2984 }
2985
2986 # For consistency with from_hex() and from_oct(), we return NaN when the
2987 # input is invalid.
2988
2989 return $self->bnan();
2990}
2991
2992sub _split
2993 {
2994 # input: num_str; output: undef for invalid or
2995 # (\$mantissa_sign,\$mantissa_value,\$mantissa_fraction,\$exp_sign,\$exp_value)
2996 # Internal, take apart a string and return the pieces.
2997 # Strip leading/trailing whitespace, leading zeros, underscore and reject
2998 # invalid input.
2999 my $x = shift;
3000
3001 # strip white space at front, also extraneous leading zeros
3002 $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2'
3003 $x =~ s/^\s+//; # but this will
3004 $x =~ s/\s+$//g; # strip white space at end
3005
3006 # shortcut, if nothing to split, return early
3007 if ($x =~ /^[+-]?[0-9]+\z/)
3008 {
3009 $x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
3010 return (\$sign, \$x, \'', \'', \0);
3011 }
3012
3013 # invalid starting char?
3014 return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
3015
3016 return Math::BigInt->from_hex($x) if $x =~ /^[+-]?0x/; # hex string
3017 return Math::BigInt->from_bin($x) if $x =~ /^[+-]?0b/; # binary string
3018
3019 # strip underscores between digits
3020 $x =~ s/([0-9])_([0-9])/$1$2/g;
3021 $x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3
3022
3023 # some possible inputs:
3024 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2
3025 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2 # 0e999
3026
3027 my ($m,$e,$last) = split /[Ee]/,$x;
3028 return if defined $last; # last defined => 1e2E3 or others
3029 $e = '0' if !defined $e || $e eq "";
3030
3031 # sign,value for exponent,mantint,mantfrac
3032 my ($es,$ev,$mis,$miv,$mfv);
3033 # valid exponent?
3034 if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
3035 {
3036 $es = $1; $ev = $2;
3037 # valid mantissa?
3038 return if $m eq '.' || $m eq '';
3039 my ($mi,$mf,$lastf) = split /\./,$m;
3040 return if defined $lastf; # lastf defined => 1.2.3 or others
3041 $mi = '0' if !defined $mi;
3042 $mi .= '0' if $mi =~ /^[\-\+]?$/;
3043 $mf = '0' if !defined $mf || $mf eq '';
3044 if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros
3045 {
3046 $mis = $1||'+'; $miv = $2;
3047 return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros
3048 $mfv = $1;
3049 # handle the 0e999 case here
3050 $ev = 0 if $miv eq '0' && $mfv eq '';
3051 return (\$mis,\$miv,\$mfv,\$es,\$ev);
3052 }
3053 }
3054 return; # NaN, not a number
3055 }
3056
3057##############################################################################
3058# internal calculation routines (others are in Math::BigInt::Calc etc)
3059
3060sub __lcm
3061 {
3062 # (BINT or num_str, BINT or num_str) return BINT
3063 # does modify first argument
3064 # LCM
3065
3066 my ($x,$ty) = @_;
3067 return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
3068 my $method = ref($x) . '::bgcd';
306921.62ms272µs
# spent 45µs (19+26) within Math::BigInt::BEGIN@3069 which was called: # once (19µs+26µs) by bigint::import at line 3069
no strict 'refs';
# spent 45µs making 1 call to Math::BigInt::BEGIN@3069 # spent 26µs making 1 call to strict::unimport
3070 $x * $ty / &$method($x,$ty);
3071 }
3072
3073###############################################################################
3074# trigonometric functions
3075
3076sub bpi
3077 {
3078 # Calculate PI to N digits. Unless upgrading is in effect, returns the
3079 # result truncated to an integer, that is, always returns '3'.
3080 my ($self,$n) = @_;
3081 if (@_ == 1)
3082 {
3083 # called like Math::BigInt::bpi(10);
3084 $n = $self; $self = $class;
3085 }
3086 $self = ref($self) if ref($self);
3087
3088 return $upgrade->new($n) if defined $upgrade;
3089
3090 # hard-wired to "3"
3091 $self->new(3);
3092 }
3093
3094sub bcos
3095 {
3096 # Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the
3097 # result truncated to an integer.
3098 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
3099
3100 return $x if $x->modify('bcos');
3101
3102 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
3103
3104 return $upgrade->new($x)->bcos(@r) if defined $upgrade;
3105
3106 require Math::BigFloat;
3107 # calculate the result and truncate it to integer
3108 my $t = Math::BigFloat->new($x)->bcos(@r)->as_int();
3109
3110 $x->bone() if $t->is_one();
3111 $x->bzero() if $t->is_zero();
3112 $x->round(@r);
3113 }
3114
3115sub bsin
3116 {
3117 # Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the
3118 # result truncated to an integer.
3119 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
3120
3121 return $x if $x->modify('bsin');
3122
3123 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
3124
3125 return $upgrade->new($x)->bsin(@r) if defined $upgrade;
3126
3127 require Math::BigFloat;
3128 # calculate the result and truncate it to integer
3129 my $t = Math::BigFloat->new($x)->bsin(@r)->as_int();
3130
3131 $x->bone() if $t->is_one();
3132 $x->bzero() if $t->is_zero();
3133 $x->round(@r);
3134 }
3135
3136sub batan2
3137 {
3138 # calculate arcus tangens of ($y/$x)
3139
3140 # set up parameters
3141 my ($self,$y,$x,@r) = (ref($_[0]),@_);
3142 # objectify is costly, so avoid it
3143 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
3144 {
3145 ($self,$y,$x,@r) = objectify(2,@_);
3146 }
3147
3148 return $y if $y->modify('batan2');
3149
3150 return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan);
3151
3152 # Y X
3153 # != 0 -inf result is +- pi
3154 if ($x->is_inf() || $y->is_inf())
3155 {
3156 # upgrade to BigFloat etc.
3157 return $upgrade->new($y)->batan2($upgrade->new($x),@r) if defined $upgrade;
3158 if ($y->is_inf())
3159 {
3160 if ($x->{sign} eq '-inf')
3161 {
3162 # calculate 3 pi/4 => 2.3.. => 2
3163 $y->bone( substr($y->{sign},0,1) );
3164 $y->bmul($self->new(2));
3165 }
3166 elsif ($x->{sign} eq '+inf')
3167 {
3168 # calculate pi/4 => 0.7 => 0
3169 $y->bzero();
3170 }
3171 else
3172 {
3173 # calculate pi/2 => 1.5 => 1
3174 $y->bone( substr($y->{sign},0,1) );
3175 }
3176 }
3177 else
3178 {
3179 if ($x->{sign} eq '+inf')
3180 {
3181 # calculate pi/4 => 0.7 => 0
3182 $y->bzero();
3183 }
3184 else
3185 {
3186 # PI => 3.1415.. => 3
3187 $y->bone( substr($y->{sign},0,1) );
3188 $y->bmul($self->new(3));
3189 }
3190 }
3191 return $y;
3192 }
3193
3194 return $upgrade->new($y)->batan2($upgrade->new($x),@r) if defined $upgrade;
3195
3196 require Math::BigFloat;
3197 my $r = Math::BigFloat->new($y)->batan2(Math::BigFloat->new($x),@r)->as_int();
3198
3199 $x->{value} = $r->{value};
3200 $x->{sign} = $r->{sign};
3201
3202 $x;
3203 }
3204
3205sub batan
3206 {
3207 # Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the
3208 # result truncated to an integer.
3209 my ($self,$x,@r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
3210
3211 return $x if $x->modify('batan');
3212
3213 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN
3214
3215 return $upgrade->new($x)->batan(@r) if defined $upgrade;
3216
3217 # calculate the result and truncate it to integer
3218 my $t = Math::BigFloat->new($x)->batan(@r);
3219
3220 $x->{value} = $CALC->_new( $x->as_int()->bstr() );
3221 $x->round(@r);
3222 }
3223
3224###############################################################################
3225# this method returns 0 if the object can be modified, or 1 if not.
3226# We use a fast constant sub() here, to avoid costly calls. Subclasses
3227# may override it with special code (f.i. Math::BigInt::Constant does so)
3228
3229sub modify () { 0; }
3230
3231122µs1;
3232__END__
 
# spent 64µs within Math::BigInt::CORE:match which was called 36 times, avg 2µs/call: # 10 times (30µs+0s) by Math::BigInt::new at line 534, avg 3µs/call # 10 times (8µs+0s) by Math::BigInt::new at line 538, avg 820ns/call # 9 times (14µs+0s) by Math::BigInt::import at line 2749, avg 2µs/call # 4 times (3µs+0s) by Math::BigInt::blsft at line 2068, avg 725ns/call # 2 times (2µs+0s) by Math::BigInt::is_zero at line 1443, avg 950ns/call # once (7µs+0s) by Math::BigInt::round_mode at line 214
sub Math::BigInt::CORE:match; # opcode
# spent 6µs within Math::BigInt::CORE:subst which was called 9 times, avg 689ns/call: # 9 times (6µs+0s) by Math::BigInt::import at line 2750, avg 689ns/call
sub Math::BigInt::CORE:subst; # opcode
# spent 1µs within Math::BigInt::modify which was called 2 times, avg 550ns/call: # 2 times (1µs+0s) by Math::BigInt::blsft at line 2067, avg 550ns/call
sub Math::BigInt::modify; # xsub