← Index
NYTProf Performance Profile   « line view »
For svc/members/upsert
  Run on Tue Jan 13 11:50:22 2015
Reported on Tue Jan 13 12:09:49 2015

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