threads::shared::queue and semaphore become Thread::Semaphore
[p5sagit/p5-mst-13.2.git] / lib / Math / BigInt.pm
1 package 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 similiar)
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
18 my $class = "Math::BigInt";
19 require 5.005;
20
21 # This is a patched v1.60, containing a fix for the "1234567890\n" bug
22 $VERSION = '1.60';
23 use Exporter;
24 @ISA =       qw( Exporter );
25 @EXPORT_OK = qw( objectify _swap bgcd blcm); 
26 use vars qw/$round_mode $accuracy $precision $div_scale $rnd_mode/;
27 use vars qw/$upgrade $downgrade/;
28 use strict;
29
30 # Inside overload, the first arg is always an object. If the original code had
31 # it reversed (like $x = 2 * $y), then the third paramater indicates this
32 # swapping. To make it work, we use a helper routine which not only reswaps the
33 # params, but also makes a new object in this case. See _swap() for details,
34 # especially the cases of operators with different classes.
35
36 # For overloaded ops with only one argument we simple use $_[0]->copy() to
37 # preserve the argument.
38
39 # Thus inheritance of overload operators becomes possible and transparent for
40 # our subclasses without the need to repeat the entire overload section there.
41
42 use overload
43 '='     =>      sub { $_[0]->copy(); },
44
45 # '+' and '-' do not use _swap, since it is a triffle slower. If you want to
46 # override _swap (if ever), then override overload of '+' and '-', too!
47 # for sub it is a bit tricky to keep b: b-a => -a+b
48 '-'     =>      sub { my $c = $_[0]->copy; $_[2] ?
49                    $c->bneg()->badd($_[1]) :
50                    $c->bsub( $_[1]) },
51 '+'     =>      sub { $_[0]->copy()->badd($_[1]); },
52
53 # some shortcuts for speed (assumes that reversed order of arguments is routed
54 # to normal '+' and we thus can always modify first arg. If this is changed,
55 # this breaks and must be adjusted.)
56 '+='    =>      sub { $_[0]->badd($_[1]); },
57 '-='    =>      sub { $_[0]->bsub($_[1]); },
58 '*='    =>      sub { $_[0]->bmul($_[1]); },
59 '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },
60 '%='    =>      sub { $_[0]->bmod($_[1]); },
61 '^='    =>      sub { $_[0]->bxor($_[1]); },
62 '&='    =>      sub { $_[0]->band($_[1]); },
63 '|='    =>      sub { $_[0]->bior($_[1]); },
64 '**='   =>      sub { $_[0]->bpow($_[1]); },
65
66 # not supported by Perl yet
67 '..'    =>      \&_pointpoint,
68
69 '<=>'   =>      sub { $_[2] ?
70                       ref($_[0])->bcmp($_[1],$_[0]) : 
71                       $_[0]->bcmp($_[1])},
72 'cmp'   =>      sub {
73          $_[2] ? 
74                "$_[1]" cmp $_[0]->bstr() :
75                $_[0]->bstr() cmp "$_[1]" },
76
77 'log'   =>      sub { $_[0]->copy()->blog(); }, 
78 'int'   =>      sub { $_[0]->copy(); }, 
79 'neg'   =>      sub { $_[0]->copy()->bneg(); }, 
80 'abs'   =>      sub { $_[0]->copy()->babs(); },
81 'sqrt'  =>      sub { $_[0]->copy()->bsqrt(); },
82 '~'     =>      sub { $_[0]->copy()->bnot(); },
83
84 '*'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmul($a[1]); },
85 '/'     =>      sub { my @a = ref($_[0])->_swap(@_);scalar $a[0]->bdiv($a[1]);},
86 '%'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bmod($a[1]); },
87 '**'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bpow($a[1]); },
88 '<<'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->blsft($a[1]); },
89 '>>'    =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->brsft($a[1]); },
90
91 '&'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->band($a[1]); },
92 '|'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bior($a[1]); },
93 '^'     =>      sub { my @a = ref($_[0])->_swap(@_); $a[0]->bxor($a[1]); },
94
95 # can modify arg of ++ and --, so avoid a new-copy for speed, but don't
96 # use $_[0]->__one(), it modifies $_[0] to be 1!
97 '++'    =>      sub { $_[0]->binc() },
98 '--'    =>      sub { $_[0]->bdec() },
99
100 # if overloaded, O(1) instead of O(N) and twice as fast for small numbers
101 'bool'  =>      sub {
102   # this kludge is needed for perl prior 5.6.0 since returning 0 here fails :-/
103   # v5.6.1 dumps on that: return !$_[0]->is_zero() || undef;                :-(
104   my $t = !$_[0]->is_zero();
105   undef $t if $t == 0;
106   $t;
107   },
108
109 # the original qw() does not work with the TIESCALAR below, why?
110 # Order of arguments unsignificant
111 '""' => sub { $_[0]->bstr(); },
112 '0+' => sub { $_[0]->numify(); }
113 ;
114
115 ##############################################################################
116 # global constants, flags and accessory
117
118 use constant MB_NEVER_ROUND => 0x0001;
119
120 my $NaNOK=1;                            # are NaNs ok?
121 my $nan = 'NaN';                        # constants for easier life
122
123 my $CALC = 'Math::BigInt::Calc';        # module to do low level math
124 my $IMPORT = 0;                         # did import() yet?
125
126 $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
127 $accuracy   = undef;
128 $precision  = undef;
129 $div_scale  = 40;
130
131 $upgrade = undef;                       # default is no upgrade
132 $downgrade = undef;                     # default is no downgrade
133
134 ##############################################################################
135 # the old code had $rnd_mode, so we need to support it, too
136
137 $rnd_mode   = 'even';
138 sub TIESCALAR  { my ($class) = @_; bless \$round_mode, $class; }
139 sub FETCH      { return $round_mode; }
140 sub STORE      { $rnd_mode = $_[0]->round_mode($_[1]); }
141
142 BEGIN { tie $rnd_mode, 'Math::BigInt'; }
143
144 ############################################################################## 
145
146 sub round_mode
147   {
148   no strict 'refs';
149   # make Class->round_mode() work
150   my $self = shift;
151   my $class = ref($self) || $self || __PACKAGE__;
152   if (defined $_[0])
153     {
154     my $m = shift;
155     die "Unknown round mode $m"
156      if $m !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
157     return ${"${class}::round_mode"} = $m;
158     }
159   return ${"${class}::round_mode"};
160   }
161
162 sub upgrade
163   {
164   no strict 'refs';
165   # make Class->upgrade() work
166   my $self = shift;
167   my $class = ref($self) || $self || __PACKAGE__;
168   # need to set new value?
169   if (@_ > 0)
170     {
171     my $u = shift;
172     return ${"${class}::upgrade"} = $u;
173     }
174   return ${"${class}::upgrade"};
175   }
176
177 sub downgrade
178   {
179   no strict 'refs';
180   # make Class->downgrade() work
181   my $self = shift;
182   my $class = ref($self) || $self || __PACKAGE__;
183   # need to set new value?
184   if (@_ > 0)
185     {
186     my $u = shift;
187     return ${"${class}::downgrade"} = $u;
188     }
189   return ${"${class}::downgrade"};
190   }
191
192 sub div_scale
193   {
194   no strict 'refs';
195   # make Class->round_mode() work
196   my $self = shift;
197   my $class = ref($self) || $self || __PACKAGE__;
198   if (defined $_[0])
199     {
200     die ('div_scale must be greater than zero') if $_[0] < 0;
201     ${"${class}::div_scale"} = shift;
202     }
203   return ${"${class}::div_scale"};
204   }
205
206 sub accuracy
207   {
208   # $x->accuracy($a);           ref($x) $a
209   # $x->accuracy();             ref($x)
210   # Class->accuracy();          class
211   # Class->accuracy($a);        class $a
212
213   my $x = shift;
214   my $class = ref($x) || $x || __PACKAGE__;
215
216   no strict 'refs';
217   # need to set new value?
218   if (@_ > 0)
219     {
220     my $a = shift;
221     die ('accuracy must not be zero') if defined $a && $a == 0;
222     if (ref($x))
223       {
224       # $object->accuracy() or fallback to global
225       $x->bround($a) if defined $a;
226       $x->{_a} = $a;                    # set/overwrite, even if not rounded
227       $x->{_p} = undef;                 # clear P
228       }
229     else
230       {
231       # set global
232       ${"${class}::accuracy"} = $a;
233       ${"${class}::precision"} = undef; # clear P
234       }
235     return $a;                          # shortcut
236     }
237
238   my $r;
239   # $object->accuracy() or fallback to global
240   $r = $x->{_a} if ref($x);
241   # but don't return global undef, when $x's accuracy is 0!
242   $r = ${"${class}::accuracy"} if !defined $r;
243   $r;
244   } 
245
246 sub precision
247   {
248   # $x->precision($p);          ref($x) $p
249   # $x->precision();            ref($x)
250   # Class->precision();         class
251   # Class->precision($p);       class $p
252
253   my $x = shift;
254   my $class = ref($x) || $x || __PACKAGE__;
255
256   no strict 'refs';
257   # need to set new value?
258   if (@_ > 0)
259     {
260     my $p = shift;
261     if (ref($x))
262       {
263       # $object->precision() or fallback to global
264       $x->bfround($p) if defined $p;
265       $x->{_p} = $p;                    # set/overwrite, even if not rounded
266       $x->{_a} = undef;                 # clear A
267       }
268     else
269       {
270       # set global
271       ${"${class}::precision"} = $p;
272       ${"${class}::accuracy"} = undef;  # clear A
273       }
274     return $p;                          # shortcut
275     }
276
277   my $r;
278   # $object->precision() or fallback to global
279   $r = $x->{_p} if ref($x);
280   # but don't return global undef, when $x's precision is 0!
281   $r = ${"${class}::precision"} if !defined $r;
282   $r;
283   } 
284
285 sub config
286   {
287   # return (later set?) configuration data as hash ref
288   my $class = shift || 'Math::BigInt';
289
290   no strict 'refs';
291   my $lib = $CALC;
292   my $cfg = {
293     lib => $lib,
294     lib_version => ${"${lib}::VERSION"},
295     class => $class,
296     };
297   foreach (
298    qw/upgrade downgrade precision accuracy round_mode VERSION div_scale/)
299     {
300     $cfg->{lc($_)} = ${"${class}::$_"};
301     };
302   $cfg;
303   }
304
305 sub _scale_a
306   { 
307   # select accuracy parameter based on precedence,
308   # used by bround() and bfround(), may return undef for scale (means no op)
309   my ($x,$s,$m,$scale,$mode) = @_;
310   $scale = $x->{_a} if !defined $scale;
311   $scale = $s if (!defined $scale);
312   $mode = $m if !defined $mode;
313   return ($scale,$mode);
314   }
315
316 sub _scale_p
317   { 
318   # select precision parameter based on precedence,
319   # used by bround() and bfround(), may return undef for scale (means no op)
320   my ($x,$s,$m,$scale,$mode) = @_;
321   $scale = $x->{_p} if !defined $scale;
322   $scale = $s if (!defined $scale);
323   $mode = $m if !defined $mode;
324   return ($scale,$mode);
325   }
326
327 ##############################################################################
328 # constructors
329
330 sub copy
331   {
332   my ($c,$x);
333   if (@_ > 1)
334     {
335     # if two arguments, the first one is the class to "swallow" subclasses
336     ($c,$x) = @_;
337     }
338   else
339     {
340     $x = shift;
341     $c = ref($x);
342     }
343   return unless ref($x); # only for objects
344
345   my $self = {}; bless $self,$c;
346   my $r;
347   foreach my $k (keys %$x)
348     {
349     if ($k eq 'value')
350       {
351       $self->{value} = $CALC->_copy($x->{value}); next;
352       }
353     if (!($r = ref($x->{$k})))
354       {
355       $self->{$k} = $x->{$k}; next;
356       }
357     if ($r eq 'SCALAR')
358       {
359       $self->{$k} = \${$x->{$k}};
360       }
361     elsif ($r eq 'ARRAY')
362       {
363       $self->{$k} = [ @{$x->{$k}} ];
364       }
365     elsif ($r eq 'HASH')
366       {
367       # only one level deep!
368       foreach my $h (keys %{$x->{$k}})
369         {
370         $self->{$k}->{$h} = $x->{$k}->{$h};
371         }
372       }
373     else # normal ref
374       {
375       my $xk = $x->{$k};
376       if ($xk->can('copy'))
377         {
378         $self->{$k} = $xk->copy();
379         }
380       else
381         {
382         $self->{$k} = $xk->new($xk);
383         }
384       }
385     }
386   $self;
387   }
388
389 sub new 
390   {
391   # create a new BigInt object from a string or another BigInt object. 
392   # see hash keys documented at top
393
394   # the argument could be an object, so avoid ||, && etc on it, this would
395   # cause costly overloaded code to be called. The only allowed ops are
396   # ref() and defined.
397
398   my ($class,$wanted,$a,$p,$r) = @_;
399  
400   # avoid numify-calls by not using || on $wanted!
401   return $class->bzero($a,$p) if !defined $wanted;      # default to 0
402   return $class->copy($wanted,$a,$p,$r)
403    if ref($wanted) && $wanted->isa($class);             # MBI or subclass
404
405   $class->import() if $IMPORT == 0;             # make require work
406   
407   my $self = bless {}, $class;
408
409   # shortcut for "normal" numbers
410   if ((!ref $wanted) && ($wanted =~ /^([+-]?)[1-9][0-9]*\z/))
411     {
412     $self->{sign} = $1 || '+';
413     my $ref = \$wanted;
414     if ($wanted =~ /^[+-]/)
415      {
416       # remove sign without touching wanted
417       my $t = $wanted; $t =~ s/^[+-]//; $ref = \$t;
418       }
419     $self->{value} = $CALC->_new($ref);
420     no strict 'refs';
421     if ( (defined $a) || (defined $p) 
422         || (defined ${"${class}::precision"})
423         || (defined ${"${class}::accuracy"}) 
424        )
425       {
426       $self->round($a,$p,$r) unless (@_ == 4 && !defined $a && !defined $p);
427       }
428     return $self;
429     }
430
431   # handle '+inf', '-inf' first
432   if ($wanted =~ /^[+-]?inf$/)
433     {
434     $self->{value} = $CALC->_zero();
435     $self->{sign} = $wanted; $self->{sign} = '+inf' if $self->{sign} eq 'inf';
436     return $self;
437     }
438   # split str in m mantissa, e exponent, i integer, f fraction, v value, s sign
439   my ($mis,$miv,$mfv,$es,$ev) = _split(\$wanted);
440   if (!ref $mis)
441     {
442     die "$wanted is not a number initialized to $class" if !$NaNOK;
443     #print "NaN 1\n";
444     $self->{value} = $CALC->_zero();
445     $self->{sign} = $nan;
446     return $self;
447     }
448   if (!ref $miv)
449     {
450     # _from_hex or _from_bin
451     $self->{value} = $mis->{value};
452     $self->{sign} = $mis->{sign};
453     return $self;       # throw away $mis
454     }
455   # make integer from mantissa by adjusting exp, then convert to bigint
456   $self->{sign} = $$mis;                        # store sign
457   $self->{value} = $CALC->_zero();              # for all the NaN cases
458   my $e = int("$$es$$ev");                      # exponent (avoid recursion)
459   if ($e > 0)
460     {
461     my $diff = $e - CORE::length($$mfv);
462     if ($diff < 0)                              # Not integer
463       {
464       #print "NOI 1\n";
465       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
466       $self->{sign} = $nan;
467       }
468     else                                        # diff >= 0
469       {
470       # adjust fraction and add it to value
471       # print "diff > 0 $$miv\n";
472       $$miv = $$miv . ($$mfv . '0' x $diff);
473       }
474     }
475   else
476     {
477     if ($$mfv ne '')                            # e <= 0
478       {
479       # fraction and negative/zero E => NOI
480       #print "NOI 2 \$\$mfv '$$mfv'\n";
481       return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
482       $self->{sign} = $nan;
483       }
484     elsif ($e < 0)
485       {
486       # xE-y, and empty mfv
487       #print "xE-y\n";
488       $e = abs($e);
489       if ($$miv !~ s/0{$e}$//)          # can strip so many zero's?
490         {
491         #print "NOI 3\n";
492         return $upgrade->new($wanted,$a,$p,$r) if defined $upgrade;
493         $self->{sign} = $nan;
494         }
495       }
496     }
497   $self->{sign} = '+' if $$miv eq '0';                  # normalize -0 => +0
498   $self->{value} = $CALC->_new($miv) if $self->{sign} =~ /^[+-]$/;
499   # if any of the globals is set, use them to round and store them inside $self
500   # do not round for new($x,undef,undef) since that is used by MBF to signal
501   # no rounding
502   $self->round($a,$p,$r) unless @_ == 4 && !defined $a && !defined $p;
503   $self;
504   }
505
506 sub bnan
507   {
508   # create a bigint 'NaN', if given a BigInt, set it to 'NaN'
509   my $self = shift;
510   $self = $class if !defined $self;
511   if (!ref($self))
512     {
513     my $c = $self; $self = {}; bless $self, $c;
514     }
515   $self->import() if $IMPORT == 0;              # make require work
516   return if $self->modify('bnan');
517   my $c = ref($self);
518   if ($self->can('_bnan'))
519     {
520     # use subclass to initialize
521     $self->_bnan();
522     }
523   else
524     {
525     # otherwise do our own thing
526     $self->{value} = $CALC->_zero();
527     }
528   $self->{sign} = $nan;
529   delete $self->{_a}; delete $self->{_p};       # rounding NaN is silly
530   return $self;
531   }
532
533 sub binf
534   {
535   # create a bigint '+-inf', if given a BigInt, set it to '+-inf'
536   # the sign is either '+', or if given, used from there
537   my $self = shift;
538   my $sign = shift; $sign = '+' if !defined $sign || $sign !~ /^-(inf)?$/;
539   $self = $class if !defined $self;
540   if (!ref($self))
541     {
542     my $c = $self; $self = {}; bless $self, $c;
543     }
544   $self->import() if $IMPORT == 0;              # make require work
545   return if $self->modify('binf');
546   my $c = ref($self);
547   if ($self->can('_binf'))
548     {
549     # use subclass to initialize
550     $self->_binf();
551     }
552   else
553     {
554     # otherwise do our own thing
555     $self->{value} = $CALC->_zero();
556     }
557   $sign = $sign . 'inf' if $sign !~ /inf$/;     # - => -inf
558   $self->{sign} = $sign;
559   ($self->{_a},$self->{_p}) = @_;               # take over requested rounding
560   return $self;
561   }
562
563 sub bzero
564   {
565   # create a bigint '+0', if given a BigInt, set it to 0
566   my $self = shift;
567   $self = $class if !defined $self;
568  
569   if (!ref($self))
570     {
571     my $c = $self; $self = {}; bless $self, $c;
572     }
573   $self->import() if $IMPORT == 0;              # make require work
574   return if $self->modify('bzero');
575
576   if ($self->can('_bzero'))
577     {
578     # use subclass to initialize
579     $self->_bzero();
580     }
581   else
582     {
583     # otherwise do our own thing
584     $self->{value} = $CALC->_zero();
585     }
586   $self->{sign} = '+';
587   if (@_ > 0)
588     {
589     if (@_ > 3)
590       {
591       # call like: $x->bzero($a,$p,$r,$y);
592       ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
593       }
594     else
595       {
596       $self->{_a} = $_[0]
597        if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
598       $self->{_p} = $_[1]
599        if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
600       }
601     }
602   $self;
603   }
604
605 sub bone
606   {
607   # create a bigint '+1' (or -1 if given sign '-'),
608   # if given a BigInt, set it to +1 or -1, respecively
609   my $self = shift;
610   my $sign = shift; $sign = '+' if !defined $sign || $sign ne '-';
611   $self = $class if !defined $self;
612  
613   if (!ref($self))
614     {
615     my $c = $self; $self = {}; bless $self, $c;
616     }
617   $self->import() if $IMPORT == 0;              # make require work
618   return if $self->modify('bone');
619
620   if ($self->can('_bone'))
621     {
622     # use subclass to initialize
623     $self->_bone();
624     }
625   else
626     {
627     # otherwise do our own thing
628     $self->{value} = $CALC->_one();
629     }
630   $self->{sign} = $sign;
631   if (@_ > 0)
632     {
633     if (@_ > 3)
634       {
635       # call like: $x->bone($sign,$a,$p,$r,$y);
636       ($self,$self->{_a},$self->{_p}) = $self->_find_round_parameters(@_);
637       }
638     else
639       {
640       $self->{_a} = $_[0]
641        if ( (!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
642       $self->{_p} = $_[1]
643        if ( (!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
644       }
645     }
646   $self;
647   }
648
649 ##############################################################################
650 # string conversation
651
652 sub bsstr
653   {
654   # (ref to BFLOAT or num_str ) return num_str
655   # Convert number from internal format to scientific string format.
656   # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
657   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
658   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
659
660   if ($x->{sign} !~ /^[+-]$/)
661     {
662     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
663     return 'inf';                                       # +inf
664     }
665   my ($m,$e) = $x->parts();
666   # e can only be positive
667   my $sign = 'e+';      
668   # MBF: my $s = $e->{sign}; $s = '' if $s eq '-'; my $sep = 'e'.$s;
669   return $m->bstr().$sign.$e->bstr();
670   }
671
672 sub bstr 
673   {
674   # make a string from bigint object
675   my $x = shift; $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); 
676   # my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
677
678   if ($x->{sign} !~ /^[+-]$/)
679     {
680     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
681     return 'inf';                                       # +inf
682     }
683   my $es = ''; $es = $x->{sign} if $x->{sign} eq '-';
684   return $es.${$CALC->_str($x->{value})};
685   }
686
687 sub numify 
688   {
689   # Make a "normal" scalar from a BigInt object
690   my $x = shift; $x = $class->new($x) unless ref $x;
691   return $x->{sign} if $x->{sign} !~ /^[+-]$/;
692   my $num = $CALC->_num($x->{value});
693   return -$num if $x->{sign} eq '-';
694   $num;
695   }
696
697 ##############################################################################
698 # public stuff (usually prefixed with "b")
699
700 sub sign
701   {
702   # return the sign of the number: +/-/-inf/+inf/NaN
703   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_); 
704   
705   $x->{sign};
706   }
707
708 sub _find_round_parameters
709   {
710   # After any operation or when calling round(), the result is rounded by
711   # regarding the A & P from arguments, local parameters, or globals.
712
713   # This procedure finds the round parameters, but it is for speed reasons
714   # duplicated in round. Otherwise, it is tested by the testsuite and used
715   # by fdiv().
716   
717   my ($self,$a,$p,$r,@args) = @_;
718   # $a accuracy, if given by caller
719   # $p precision, if given by caller
720   # $r round_mode, if given by caller
721   # @args all 'other' arguments (0 for unary, 1 for binary ops)
722
723   # leave bigfloat parts alone
724   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
725
726   my $c = ref($self);                           # find out class of argument(s)
727   no strict 'refs';
728
729   # now pick $a or $p, but only if we have got "arguments"
730   if (!defined $a)
731     {
732     foreach ($self,@args)
733       {
734       # take the defined one, or if both defined, the one that is smaller
735       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
736       }
737     }
738   if (!defined $p)
739     {
740     # even if $a is defined, take $p, to signal error for both defined
741     foreach ($self,@args)
742       {
743       # take the defined one, or if both defined, the one that is bigger
744       # -2 > -3, and 3 > 2
745       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
746       }
747     }
748   # if still none defined, use globals (#2)
749   $a = ${"$c\::accuracy"} unless defined $a;
750   $p = ${"$c\::precision"} unless defined $p;
751  
752   # no rounding today? 
753   return ($self) unless defined $a || defined $p;               # early out
754
755   # set A and set P is an fatal error
756   return ($self->bnan()) if defined $a && defined $p;
757
758   $r = ${"$c\::round_mode"} unless defined $r;
759   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
760  
761   return ($self,$a,$p,$r);
762   }
763
764 sub round
765   {
766   # Round $self according to given parameters, or given second argument's
767   # parameters or global defaults 
768
769   # for speed reasons, _find_round_parameters is embeded here:
770
771   my ($self,$a,$p,$r,@args) = @_;
772   # $a accuracy, if given by caller
773   # $p precision, if given by caller
774   # $r round_mode, if given by caller
775   # @args all 'other' arguments (0 for unary, 1 for binary ops)
776
777   # leave bigfloat parts alone
778   return ($self) if exists $self->{_f} && $self->{_f} & MB_NEVER_ROUND != 0;
779
780   my $c = ref($self);                           # find out class of argument(s)
781   no strict 'refs';
782
783   # now pick $a or $p, but only if we have got "arguments"
784   if (!defined $a)
785     {
786     foreach ($self,@args)
787       {
788       # take the defined one, or if both defined, the one that is smaller
789       $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a);
790       }
791     }
792   if (!defined $p)
793     {
794     # even if $a is defined, take $p, to signal error for both defined
795     foreach ($self,@args)
796       {
797       # take the defined one, or if both defined, the one that is bigger
798       # -2 > -3, and 3 > 2
799       $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p);
800       }
801     }
802   # if still none defined, use globals (#2)
803   $a = ${"$c\::accuracy"} unless defined $a;
804   $p = ${"$c\::precision"} unless defined $p;
805  
806   # no rounding today? 
807   return $self unless defined $a || defined $p;         # early out
808
809   # set A and set P is an fatal error
810   return $self->bnan() if defined $a && defined $p;
811
812   $r = ${"$c\::round_mode"} unless defined $r;
813   die "Unknown round mode '$r'" if $r !~ /^(even|odd|\+inf|\-inf|zero|trunc)$/;
814
815   # now round, by calling either fround or ffround:
816   if (defined $a)
817     {
818     $self->bround($a,$r) if !defined $self->{_a} || $self->{_a} >= $a;
819     }
820   else # both can't be undefined due to early out
821     {
822     $self->bfround($p,$r) if !defined $self->{_p} || $self->{_p} <= $p;
823     }
824   $self->bnorm();                       # after round, normalize
825   }
826
827 sub bnorm
828   { 
829   # (numstr or BINT) return BINT
830   # Normalize number -- no-op here
831   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
832   $x;
833   }
834
835 sub babs 
836   {
837   # (BINT or num_str) return BINT
838   # make number absolute, or return absolute BINT from string
839   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
840
841   return $x if $x->modify('babs');
842   # post-normalized abs for internal use (does nothing for NaN)
843   $x->{sign} =~ s/^-/+/;
844   $x;
845   }
846
847 sub bneg 
848   { 
849   # (BINT or num_str) return BINT
850   # negate number or make a negated number from string
851   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
852   
853   return $x if $x->modify('bneg');
854
855   # for +0 dont negate (to have always normalized)
856   $x->{sign} =~ tr/+-/-+/ if !$x->is_zero();    # does nothing for NaN
857   $x;
858   }
859
860 sub bcmp 
861   {
862   # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
863   # (BINT or num_str, BINT or num_str) return cond_code
864   
865   # set up parameters
866   my ($self,$x,$y) = (ref($_[0]),@_);
867
868   # objectify is costly, so avoid it 
869   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
870     {
871     ($self,$x,$y) = objectify(2,@_);
872     }
873
874   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
875     {
876     # handle +-inf and NaN
877     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
878     return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/;
879     return +1 if $x->{sign} eq '+inf';
880     return -1 if $x->{sign} eq '-inf';
881     return -1 if $y->{sign} eq '+inf';
882     return +1;
883     }
884   # check sign for speed first
885   return 1 if $x->{sign} eq '+' && $y->{sign} eq '-';   # does also 0 <=> -y
886   return -1 if $x->{sign} eq '-' && $y->{sign} eq '+';  # does also -x <=> 0 
887
888   # have same sign, so compare absolute values. Don't make tests for zero here
889   # because it's actually slower than testin in Calc (especially w/ Pari et al)
890
891   # post-normalized compare for internal use (honors signs)
892   if ($x->{sign} eq '+') 
893     {
894     # $x and $y both > 0
895     return $CALC->_acmp($x->{value},$y->{value});
896     }
897
898   # $x && $y both < 0
899   $CALC->_acmp($y->{value},$x->{value});        # swaped (lib returns 0,1,-1)
900   }
901
902 sub bacmp 
903   {
904   # Compares 2 values, ignoring their signs. 
905   # Returns one of undef, <0, =0, >0. (suitable for sort)
906   # (BINT, BINT) return cond_code
907   
908   # set up parameters
909   my ($self,$x,$y) = (ref($_[0]),@_);
910   # objectify is costly, so avoid it 
911   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
912     {
913     ($self,$x,$y) = objectify(2,@_);
914     }
915
916   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
917     {
918     # handle +-inf and NaN
919     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
920     return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/;
921     return +1;  # inf is always bigger
922     }
923   $CALC->_acmp($x->{value},$y->{value});        # lib does only 0,1,-1
924   }
925
926 sub badd 
927   {
928   # add second arg (BINT or string) to first (BINT) (modifies first)
929   # return result as BINT
930
931   # set up parameters
932   my ($self,$x,$y,@r) = (ref($_[0]),@_);
933   # objectify is costly, so avoid it 
934   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
935     {
936     ($self,$x,$y,@r) = objectify(2,@_);
937     }
938
939   return $x if $x->modify('badd');
940   return $upgrade->badd($x,$y,@r) if defined $upgrade &&
941     ((!$x->isa($self)) || (!$y->isa($self)));
942
943   $r[3] = $y;                           # no push!
944   # inf and NaN handling
945   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
946     {
947     # NaN first
948     return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
949     # inf handling
950     if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
951       {
952       # +inf++inf or -inf+-inf => same, rest is NaN
953       return $x if $x->{sign} eq $y->{sign};
954       return $x->bnan();
955       }
956     # +-inf + something => +inf
957     # something +-inf => +-inf
958     $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
959     return $x;
960     }
961     
962   my ($sx, $sy) = ( $x->{sign}, $y->{sign} ); # get signs
963
964   if ($sx eq $sy)  
965     {
966     $x->{value} = $CALC->_add($x->{value},$y->{value}); # same sign, abs add
967     $x->{sign} = $sx;
968     }
969   else 
970     {
971     my $a = $CALC->_acmp ($y->{value},$x->{value});     # absolute compare
972     if ($a > 0)                           
973       {
974       #print "swapped sub (a=$a)\n";
975       $x->{value} = $CALC->_sub($y->{value},$x->{value},1); # abs sub w/ swap
976       $x->{sign} = $sy;
977       } 
978     elsif ($a == 0)
979       {
980       # speedup, if equal, set result to 0
981       #print "equal sub, result = 0\n";
982       $x->{value} = $CALC->_zero();
983       $x->{sign} = '+';
984       }
985     else # a < 0
986       {
987       #print "unswapped sub (a=$a)\n";
988       $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub
989       $x->{sign} = $sx;
990       }
991     }
992   $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
993   $x;
994   }
995
996 sub bsub 
997   {
998   # (BINT or num_str, BINT or num_str) return num_str
999   # subtract second arg from first, modify first
1000   
1001   # set up parameters
1002   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1003   # objectify is costly, so avoid it
1004   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1005     {
1006     ($self,$x,$y,@r) = objectify(2,@_);
1007     }
1008
1009   return $x if $x->modify('bsub');
1010
1011 # upgrade done by badd():
1012 #  return $upgrade->badd($x,$y,@r) if defined $upgrade &&
1013 #   ((!$x->isa($self)) || (!$y->isa($self)));
1014
1015   if ($y->is_zero())
1016     { 
1017     $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1018     return $x;
1019     }
1020
1021   $y->{sign} =~ tr/+\-/-+/;     # does nothing for NaN
1022   $x->badd($y,@r);              # badd does not leave internal zeros
1023   $y->{sign} =~ tr/+\-/-+/;     # refix $y (does nothing for NaN)
1024   $x;                           # already rounded by badd() or no round necc.
1025   }
1026
1027 sub binc
1028   {
1029   # increment arg by one
1030   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1031   return $x if $x->modify('binc');
1032
1033   if ($x->{sign} eq '+')
1034     {
1035     $x->{value} = $CALC->_inc($x->{value});
1036     $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1037     return $x;
1038     }
1039   elsif ($x->{sign} eq '-')
1040     {
1041     $x->{value} = $CALC->_dec($x->{value});
1042     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1043     $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1044     return $x;
1045     }
1046   # inf, nan handling etc
1047   $x->badd($self->__one(),$a,$p,$r);            # badd does round
1048   }
1049
1050 sub bdec
1051   {
1052   # decrement arg by one
1053   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1054   return $x if $x->modify('bdec');
1055   
1056   my $zero = $CALC->_is_zero($x->{value}) && $x->{sign} eq '+';
1057   # <= 0
1058   if (($x->{sign} eq '-') || $zero) 
1059     {
1060     $x->{value} = $CALC->_inc($x->{value});
1061     $x->{sign} = '-' if $zero;                  # 0 => 1 => -1
1062     $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0
1063     $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1064     return $x;
1065     }
1066   # > 0
1067   elsif ($x->{sign} eq '+')
1068     {
1069     $x->{value} = $CALC->_dec($x->{value});
1070     $x->round($a,$p,$r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1071     return $x;
1072     }
1073   # inf, nan handling etc
1074   $x->badd($self->__one('-'),$a,$p,$r);                 # badd does round
1075   } 
1076
1077 sub blog
1078   {
1079   # not implemented yet
1080   my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1081  
1082   return $upgrade->blog($x,$base,$a,$p,$r) if defined $upgrade;
1083
1084   return $x->bnan();
1085   }
1086  
1087 sub blcm 
1088   { 
1089   # (BINT or num_str, BINT or num_str) return BINT
1090   # does not modify arguments, but returns new object
1091   # Lowest Common Multiplicator
1092
1093   my $y = shift; my ($x);
1094   if (ref($y))
1095     {
1096     $x = $y->copy();
1097     }
1098   else
1099     {
1100     $x = $class->new($y);
1101     }
1102   while (@_) { $x = __lcm($x,shift); } 
1103   $x;
1104   }
1105
1106 sub bgcd 
1107   { 
1108   # (BINT or num_str, BINT or num_str) return BINT
1109   # does not modify arguments, but returns new object
1110   # GCD -- Euclids algorithm, variant C (Knuth Vol 3, pg 341 ff)
1111
1112   my $y = shift;
1113   $y = __PACKAGE__->new($y) if !ref($y);
1114   my $self = ref($y);
1115   my $x = $y->copy();           # keep arguments
1116   if ($CALC->can('_gcd'))
1117     {
1118     while (@_)
1119       {
1120       $y = shift; $y = $self->new($y) if !ref($y);
1121       next if $y->is_zero();
1122       return $x->bnan() if $y->{sign} !~ /^[+-]$/;      # y NaN?
1123       $x->{value} = $CALC->_gcd($x->{value},$y->{value}); last if $x->is_one();
1124       }
1125     }
1126   else
1127     {
1128     while (@_)
1129       {
1130       $y = shift; $y = $self->new($y) if !ref($y);
1131       $x = __gcd($x,$y->copy()); last if $x->is_one();  # _gcd handles NaN
1132       } 
1133     }
1134   $x->babs();
1135   }
1136
1137 sub bnot 
1138   {
1139   # (num_str or BINT) return BINT
1140   # represent ~x as twos-complement number
1141   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1142   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1143  
1144   return $x if $x->modify('bnot');
1145   $x->bneg()->bdec();                   # bdec already does round
1146   }
1147
1148 # is_foo test routines
1149
1150 sub is_zero
1151   {
1152   # return true if arg (BINT or num_str) is zero (array '+', '0')
1153   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1154   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1155   
1156   return 0 if $x->{sign} !~ /^\+$/;                     # -, NaN & +-inf aren't
1157   $CALC->_is_zero($x->{value});
1158   }
1159
1160 sub is_nan
1161   {
1162   # return true if arg (BINT or num_str) is NaN
1163   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1164
1165   return 1 if $x->{sign} eq $nan;
1166   0;
1167   }
1168
1169 sub is_inf
1170   {
1171   # return true if arg (BINT or num_str) is +-inf
1172   my ($self,$x,$sign) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1173
1174   $sign = '' if !defined $sign;
1175   return 1 if $sign eq $x->{sign};              # match ("+inf" eq "+inf")
1176   return 0 if $sign !~ /^([+-]|)$/;
1177
1178   if ($sign eq '')
1179     {
1180     return 1 if ($x->{sign} =~ /^[+-]inf$/); 
1181     return 0;
1182     }
1183   $sign = quotemeta($sign.'inf');
1184   return 1 if ($x->{sign} =~ /^$sign$/);
1185   0;
1186   }
1187
1188 sub is_one
1189   {
1190   # return true if arg (BINT or num_str) is +1
1191   # or -1 if sign is given
1192   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1193   my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
1194     
1195   $sign = '' if !defined $sign; $sign = '+' if $sign ne '-';
1196  
1197   return 0 if $x->{sign} ne $sign;      # -1 != +1, NaN, +-inf aren't either
1198   $CALC->_is_one($x->{value});
1199   }
1200
1201 sub is_odd
1202   {
1203   # return true when arg (BINT or num_str) is odd, false for even
1204   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1205   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1206
1207   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1208   $CALC->_is_odd($x->{value});
1209   }
1210
1211 sub is_even
1212   {
1213   # return true when arg (BINT or num_str) is even, false for odd
1214   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1215   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1216
1217   return 0 if $x->{sign} !~ /^[+-]$/;                   # NaN & +-inf aren't
1218   $CALC->_is_even($x->{value});
1219   }
1220
1221 sub is_positive
1222   {
1223   # return true when arg (BINT or num_str) is positive (>= 0)
1224   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1225   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1226   
1227   return 1 if $x->{sign} =~ /^\+/;
1228   0;
1229   }
1230
1231 sub is_negative
1232   {
1233   # return true when arg (BINT or num_str) is negative (< 0)
1234   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1235   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1236   
1237   return 1 if ($x->{sign} =~ /^-/);
1238   0;
1239   }
1240
1241 sub is_int
1242   {
1243   # return true when arg (BINT or num_str) is an integer
1244   # always true for BigInt, but different for Floats
1245   # we don't need $self, so undef instead of ref($_[0]) make it slightly faster
1246   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
1247   
1248   $x->{sign} =~ /^[+-]$/ ? 1 : 0;               # inf/-inf/NaN aren't
1249   }
1250
1251 ###############################################################################
1252
1253 sub bmul 
1254   { 
1255   # multiply two numbers -- stolen from Knuth Vol 2 pg 233
1256   # (BINT or num_str, BINT or num_str) return BINT
1257
1258   # set up parameters
1259   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1260   # objectify is costly, so avoid it
1261   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1262     {
1263     ($self,$x,$y,@r) = objectify(2,@_);
1264     }
1265   
1266   return $x if $x->modify('bmul');
1267
1268   return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
1269
1270   # inf handling
1271   if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
1272     {
1273     return $x->bnan() if $x->is_zero() || $y->is_zero();
1274     # result will always be +-inf:
1275     # +inf * +/+inf => +inf, -inf * -/-inf => +inf
1276     # +inf * -/-inf => -inf, -inf * +/+inf => -inf
1277     return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); 
1278     return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); 
1279     return $x->binf('-');
1280     }
1281   
1282   return $upgrade->bmul($x,$y,@r)
1283    if defined $upgrade && $y->isa($upgrade);
1284   
1285   $r[3] = $y;                           # no push here
1286
1287   $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => +
1288
1289   $x->{value} = $CALC->_mul($x->{value},$y->{value});   # do actual math
1290   $x->{sign} = '+' if $CALC->_is_zero($x->{value});     # no -0
1291
1292   $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1293   $x;
1294   }
1295
1296 sub _div_inf
1297   {
1298   # helper function that handles +-inf cases for bdiv()/bmod() to reuse code
1299   my ($self,$x,$y) = @_;
1300
1301   # NaN if x == NaN or y == NaN or x==y==0
1302   return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan()
1303    if (($x->is_nan() || $y->is_nan())   ||
1304        ($x->is_zero() && $y->is_zero()));
1305  
1306   # +-inf / +-inf == NaN, reminder also NaN
1307   if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
1308     {
1309     return wantarray ? ($x->bnan(),$self->bnan()) : $x->bnan();
1310     }
1311   # x / +-inf => 0, remainder x (works even if x == 0)
1312   if ($y->{sign} =~ /^[+-]inf$/)
1313     {
1314     my $t = $x->copy();         # bzero clobbers up $x
1315     return wantarray ? ($x->bzero(),$t) : $x->bzero()
1316     }
1317   
1318   # 5 / 0 => +inf, -6 / 0 => -inf
1319   # +inf / 0 = inf, inf,  and -inf / 0 => -inf, -inf 
1320   # exception:   -8 / 0 has remainder -8, not 8
1321   # exception: -inf / 0 has remainder -inf, not inf
1322   if ($y->is_zero())
1323     {
1324     # +-inf / 0 => special case for -inf
1325     return wantarray ?  ($x,$x->copy()) : $x if $x->is_inf();
1326     if (!$x->is_zero() && !$x->is_inf())
1327       {
1328       my $t = $x->copy();               # binf clobbers up $x
1329       return wantarray ?
1330        ($x->binf($x->{sign}),$t) : $x->binf($x->{sign})
1331       }
1332     }
1333   
1334   # last case: +-inf / ordinary number
1335   my $sign = '+inf';
1336   $sign = '-inf' if substr($x->{sign},0,1) ne $y->{sign};
1337   $x->{sign} = $sign;
1338   return wantarray ? ($x,$self->bzero()) : $x;
1339   }
1340
1341 sub bdiv 
1342   {
1343   # (dividend: BINT or num_str, divisor: BINT or num_str) return 
1344   # (BINT,BINT) (quo,rem) or BINT (only rem)
1345   
1346   # set up parameters
1347   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1348   # objectify is costly, so avoid it 
1349   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1350     {
1351     ($self,$x,$y,@r) = objectify(2,@_);
1352     } 
1353
1354   return $x if $x->modify('bdiv');
1355
1356   return $self->_div_inf($x,$y)
1357    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
1358
1359   return $upgrade->bdiv($upgrade->new($x),$y,@r)
1360    if defined $upgrade && !$y->isa($self);
1361
1362   $r[3] = $y;                                   # no push!
1363
1364   # 0 / something
1365   return
1366    wantarray ? ($x->round(@r),$self->bzero(@r)):$x->round(@r) if $x->is_zero();
1367  
1368   # Is $x in the interval [0, $y) (aka $x <= $y) ?
1369   my $cmp = $CALC->_acmp($x->{value},$y->{value});
1370   if (($cmp < 0) and (($x->{sign} eq $y->{sign}) or !wantarray))
1371     {
1372     return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1373      if defined $upgrade;
1374
1375     return $x->bzero()->round(@r) unless wantarray;
1376     my $t = $x->copy();      # make copy first, because $x->bzero() clobbers $x
1377     return ($x->bzero()->round(@r),$t);
1378     }
1379   elsif ($cmp == 0)
1380     {
1381     # shortcut, both are the same, so set to +/- 1
1382     $x->__one( ($x->{sign} ne $y->{sign} ? '-' : '+') ); 
1383     return $x unless wantarray;
1384     return ($x->round(@r),$self->bzero(@r));
1385     }
1386   return $upgrade->bdiv($upgrade->new($x),$upgrade->new($y),@r)
1387    if defined $upgrade;
1388    
1389   # calc new sign and in case $y == +/- 1, return $x
1390   my $xsign = $x->{sign};                               # keep
1391   $x->{sign} = ($x->{sign} ne $y->{sign} ? '-' : '+'); 
1392   # check for / +-1 (cant use $y->is_one due to '-'
1393   if ($CALC->_is_one($y->{value}))
1394     {
1395     return wantarray ? ($x->round(@r),$self->bzero(@r)) : $x->round(@r); 
1396     }
1397
1398   if (wantarray)
1399     {
1400     my $rem = $self->bzero(); 
1401     ($x->{value},$rem->{value}) = $CALC->_div($x->{value},$y->{value});
1402     $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1403     $rem->{_a} = $x->{_a};
1404     $rem->{_p} = $x->{_p};
1405     $x->round(@r); 
1406     if (! $CALC->_is_zero($rem->{value}))
1407       {
1408       $rem->{sign} = $y->{sign};
1409       $rem = $y-$rem if $xsign ne $y->{sign};   # one of them '-'
1410       }
1411     else
1412       {
1413       $rem->{sign} = '+';                       # dont leave -0
1414       }
1415     return ($x,$rem->round(@r));
1416     }
1417
1418   $x->{value} = $CALC->_div($x->{value},$y->{value});
1419   $x->{sign} = '+' if $CALC->_is_zero($x->{value});
1420
1421   $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1422   $x;
1423   }
1424
1425 ###############################################################################
1426 # modulus functions
1427
1428 sub bmod 
1429   {
1430   # modulus (or remainder)
1431   # (BINT or num_str, BINT or num_str) return BINT
1432   
1433   # set up parameters
1434   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1435   # objectify is costly, so avoid it
1436   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1437     {
1438     ($self,$x,$y,@r) = objectify(2,@_);
1439     }
1440
1441   return $x if $x->modify('bmod');
1442   $r[3] = $y;                                   # no push!
1443   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero())
1444     {
1445     my ($d,$r) = $self->_div_inf($x,$y);
1446     $x->{sign} = $r->{sign};
1447     $x->{value} = $r->{value};
1448     return $x->round(@r);
1449     }
1450
1451   if ($CALC->can('_mod'))
1452     {
1453     # calc new sign and in case $y == +/- 1, return $x
1454     $x->{value} = $CALC->_mod($x->{value},$y->{value});
1455     if (!$CALC->_is_zero($x->{value}))
1456       {
1457       my $xsign = $x->{sign};
1458       $x->{sign} = $y->{sign};
1459       if ($xsign ne $y->{sign})
1460         {
1461         my $t = $CALC->_copy($x->{value});              # copy $x
1462         $x->{value} = $CALC->_copy($y->{value});        # copy $y to $x
1463         $x->{value} = $CALC->_sub($y->{value},$t,1);    # $y-$x
1464         }
1465       }
1466     else
1467       {
1468       $x->{sign} = '+';                         # dont leave -0
1469       }
1470     $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1471     return $x;
1472     }
1473   my ($t,$rem) = $self->bdiv($x->copy(),$y,@r); # slow way (also rounds)
1474   # modify in place
1475   foreach (qw/value sign _a _p/)
1476     {
1477     $x->{$_} = $rem->{$_};
1478     }
1479   $x;
1480   }
1481
1482 sub bmodinv
1483   {
1484   # modular inverse.  given a number which is (hopefully) relatively
1485   # prime to the modulus, calculate its inverse using Euclid's
1486   # alogrithm.  if the number is not relatively prime to the modulus
1487   # (i.e. their gcd is not one) then NaN is returned.
1488
1489   # set up parameters
1490   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1491   # objectify is costly, so avoid it 
1492   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1493     {
1494     ($self,$x,$y,@r) = objectify(2,@_);
1495     } 
1496
1497   return $x if $x->modify('bmodinv');
1498
1499   return $x->bnan()
1500         if ($y->{sign} ne '+'                           # -, NaN, +inf, -inf
1501          || $x->is_zero()                               # or num == 0
1502          || $x->{sign} !~ /^[+-]$/                      # or num NaN, inf, -inf
1503         );
1504
1505   # put least residue into $x if $x was negative, and thus make it positive
1506   $x->bmod($y) if $x->{sign} eq '-';
1507
1508   if ($CALC->can('_modinv'))
1509     {
1510     $x->{value} = $CALC->_modinv($x->{value},$y->{value});
1511     $x->bnan() if !defined $x->{value} ;            # in case there was none
1512     return $x;
1513     }
1514
1515   my ($u, $u1) = ($self->bzero(), $self->bone());
1516   my ($a, $b) = ($y->copy(), $x->copy());
1517
1518   # first step need always be done since $num (and thus $b) is never 0
1519   # Note that the loop is aligned so that the check occurs between #2 and #1
1520   # thus saving us one step #2 at the loop end. Typical loop count is 1. Even
1521   # a case with 28 loops still gains about 3% with this layout.
1522   my $q;
1523   ($a, $q, $b) = ($b, $a->bdiv($b));                    # step #1
1524   # Euclid's Algorithm
1525   while (!$b->is_zero())
1526     {
1527     ($u, $u1) = ($u1, $u->bsub($u1->copy()->bmul($q))); # step #2
1528     ($a, $q, $b) = ($b, $a->bdiv($b));                  # step #1 again
1529     }
1530
1531   # if the gcd is not 1, then return NaN!  It would be pointless to
1532   # have called bgcd to check this first, because we would then be performing
1533   # the same Euclidean Algorithm *twice*
1534   return $x->bnan() unless $a->is_one();
1535
1536   $u1->bmod($y);
1537   $x->{value} = $u1->{value};
1538   $x->{sign} = $u1->{sign};
1539   $x;
1540   }
1541
1542 sub bmodpow
1543   {
1544   # takes a very large number to a very large exponent in a given very
1545   # large modulus, quickly, thanks to binary exponentation.  supports
1546   # negative exponents.
1547   my ($self,$num,$exp,$mod,@r) = objectify(3,@_);
1548
1549   return $num if $num->modify('bmodpow');
1550
1551   # check modulus for valid values
1552   return $num->bnan() if ($mod->{sign} ne '+'           # NaN, - , -inf, +inf
1553                        || $mod->is_zero());
1554
1555   # check exponent for valid values
1556   if ($exp->{sign} =~ /\w/) 
1557     {
1558     # i.e., if it's NaN, +inf, or -inf...
1559     return $num->bnan();
1560     }
1561
1562   $num->bmodinv ($mod) if ($exp->{sign} eq '-');
1563
1564   # check num for valid values (also NaN if there was no inverse but $exp < 0)
1565   return $num->bnan() if $num->{sign} !~ /^[+-]$/;
1566
1567   if ($CALC->can('_modpow'))
1568     {
1569     # $mod is positive, sign on $exp is ignored, result also positive
1570     $num->{value} = $CALC->_modpow($num->{value},$exp->{value},$mod->{value});
1571     return $num;
1572     }
1573
1574   # in the trivial case,
1575   return $num->bzero(@r) if $mod->is_one();
1576   return $num->bone('+',@r) if $num->is_zero() or $num->is_one();
1577
1578   # $num->bmod($mod);           # if $x is large, make it smaller first
1579   my $acc = $num->copy();       # but this is not really faster...
1580
1581   $num->bone(); # keep ref to $num
1582
1583   my $expbin = $exp->as_bin(); $expbin =~ s/^[-]?0b//; # ignore sign and prefix
1584   my $len = length($expbin);
1585   while (--$len >= 0)
1586     {
1587     if( substr($expbin,$len,1) eq '1')
1588       {
1589       $num->bmul($acc)->bmod($mod);
1590       }
1591     $acc->bmul($acc)->bmod($mod);
1592     }
1593
1594   $num;
1595   }
1596
1597 ###############################################################################
1598
1599 sub bfac
1600   {
1601   # (BINT or num_str, BINT or num_str) return BINT
1602   # compute factorial numbers
1603   # modifies first argument
1604   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1605
1606   return $x if $x->modify('bfac');
1607  
1608   return $x->bnan() if $x->{sign} ne '+';       # inf, NnN, <0 etc => NaN
1609   return $x->bone('+',@r) if $x->is_zero() || $x->is_one();     # 0 or 1 => 1
1610
1611   if ($CALC->can('_fac'))
1612     {
1613     $x->{value} = $CALC->_fac($x->{value});
1614     return $x->round(@r);
1615     }
1616
1617   my $n = $x->copy();
1618   $x->bone();
1619   # seems we need not to temp. clear A/P of $x since the result is the same
1620   my $f = $self->new(2);
1621   while ($f->bacmp($n) < 0)
1622     {
1623     $x->bmul($f); $f->binc();
1624     }
1625   $x->bmul($f,@r);                      # last step and also round
1626   }
1627  
1628 sub bpow 
1629   {
1630   # (BINT or num_str, BINT or num_str) return BINT
1631   # compute power of two numbers -- stolen from Knuth Vol 2 pg 233
1632   # modifies first argument
1633   
1634   # set up parameters
1635   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1636   # objectify is costly, so avoid it
1637   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1638     {
1639     ($self,$x,$y,@r) = objectify(2,@_);
1640     }
1641
1642   return $x if $x->modify('bpow');
1643
1644   return $upgrade->bpow($upgrade->new($x),$y,@r)
1645    if defined $upgrade && !$y->isa($self);
1646
1647   $r[3] = $y;                                   # no push!
1648   return $x if $x->{sign} =~ /^[+-]inf$/;       # -inf/+inf ** x
1649   return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
1650   return $x->bone('+',@r) if $y->is_zero();
1651   return $x->round(@r) if $x->is_one() || $y->is_one();
1652   if ($x->{sign} eq '-' && $CALC->_is_one($x->{value}))
1653     {
1654     # if $x == -1 and odd/even y => +1/-1
1655     return $y->is_odd() ? $x->round(@r) : $x->babs()->round(@r);
1656     # my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
1657     }
1658   # 1 ** -y => 1 / (1 ** |y|)
1659   # so do test for negative $y after above's clause
1660   return $x->bnan() if $y->{sign} eq '-';
1661   return $x->round(@r) if $x->is_zero();  # 0**y => 0 (if not y <= 0)
1662
1663   if ($CALC->can('_pow'))
1664     {
1665     $x->{value} = $CALC->_pow($x->{value},$y->{value});
1666     $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1667     return $x;
1668     }
1669
1670 # based on the assumption that shifting in base 10 is fast, and that mul
1671 # works faster if numbers are small: we count trailing zeros (this step is
1672 # O(1)..O(N), but in case of O(N) we save much more time due to this),
1673 # stripping them out of the multiplication, and add $count * $y zeros
1674 # afterwards like this:
1675 # 300 ** 3 == 300*300*300 == 3*3*3 . '0' x 2 * 3 == 27 . '0' x 6
1676 # creates deep recursion since brsft/blsft use bpow sometimes.
1677 #  my $zeros = $x->_trailing_zeros();
1678 #  if ($zeros > 0)
1679 #    {
1680 #    $x->brsft($zeros,10);      # remove zeros
1681 #    $x->bpow($y);              # recursion (will not branch into here again)
1682 #    $zeros = $y * $zeros;      # real number of zeros to add
1683 #    $x->blsft($zeros,10);
1684 #    return $x->round(@r);
1685 #    }
1686
1687   my $pow2 = $self->__one();
1688   my $y_bin = $y->as_bin(); $y_bin =~ s/^0b//;
1689   my $len = length($y_bin);
1690   while (--$len > 0)
1691     {
1692     $pow2->bmul($x) if substr($y_bin,$len,1) eq '1';    # is odd?
1693     $x->bmul($x);
1694     }
1695   $x->bmul($pow2);
1696   $x->round(@r) if !exists $x->{_f} || $x->{_f} & MB_NEVER_ROUND == 0;
1697   $x;
1698   }
1699
1700 sub blsft 
1701   {
1702   # (BINT or num_str, BINT or num_str) return BINT
1703   # compute x << y, base n, y >= 0
1704  
1705   # set up parameters
1706   my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
1707   # objectify is costly, so avoid it
1708   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1709     {
1710     ($self,$x,$y,$n,@r) = objectify(2,@_);
1711     }
1712
1713   return $x if $x->modify('blsft');
1714   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1715   return $x->round(@r) if $y->is_zero();
1716
1717   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1718
1719   my $t; $t = $CALC->_lsft($x->{value},$y->{value},$n) if $CALC->can('_lsft');
1720   if (defined $t)
1721     {
1722     $x->{value} = $t; return $x->round(@r);
1723     }
1724   # fallback
1725   return $x->bmul( $self->bpow($n, $y, @r), @r );
1726   }
1727
1728 sub brsft 
1729   {
1730   # (BINT or num_str, BINT or num_str) return BINT
1731   # compute x >> y, base n, y >= 0
1732   
1733   # set up parameters
1734   my ($self,$x,$y,$n,@r) = (ref($_[0]),@_);
1735   # objectify is costly, so avoid it
1736   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1737     {
1738     ($self,$x,$y,$n,@r) = objectify(2,@_);
1739     }
1740
1741   return $x if $x->modify('brsft');
1742   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1743   return $x->round(@r) if $y->is_zero();
1744   return $x->bzero(@r) if $x->is_zero();                # 0 => 0
1745
1746   $n = 2 if !defined $n; return $x->bnan() if $n <= 0 || $y->{sign} eq '-';
1747
1748    # this only works for negative numbers when shifting in base 2
1749   if (($x->{sign} eq '-') && ($n == 2))
1750     {
1751     return $x->round(@r) if $x->is_one('-');    # -1 => -1
1752     if (!$y->is_one())
1753       {
1754       # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et al
1755       # but perhaps there is a better emulation for two's complement shift...
1756       # if $y != 1, we must simulate it by doing:
1757       # convert to bin, flip all bits, shift, and be done
1758       $x->binc();                       # -3 => -2
1759       my $bin = $x->as_bin();
1760       $bin =~ s/^-0b//;                 # strip '-0b' prefix
1761       $bin =~ tr/10/01/;                # flip bits
1762       # now shift
1763       if (CORE::length($bin) <= $y)
1764         {
1765         $bin = '0';                     # shifting to far right creates -1
1766                                         # 0, because later increment makes 
1767                                         # that 1, attached '-' makes it '-1'
1768                                         # because -1 >> x == -1 !
1769         } 
1770       else
1771         {
1772         $bin =~ s/.{$y}$//;             # cut off at the right side
1773         $bin = '1' . $bin;              # extend left side by one dummy '1'
1774         $bin =~ tr/10/01/;              # flip bits back
1775         }
1776       my $res = $self->new('0b'.$bin);  # add prefix and convert back
1777       $res->binc();                     # remember to increment
1778       $x->{value} = $res->{value};      # take over value
1779       return $x->round(@r);             # we are done now, magic, isn't?
1780       }
1781     $x->bdec();                         # n == 2, but $y == 1: this fixes it
1782     }
1783
1784   my $t; $t = $CALC->_rsft($x->{value},$y->{value},$n) if $CALC->can('_rsft');
1785   if (defined $t)
1786     {
1787     $x->{value} = $t;
1788     return $x->round(@r);
1789     }
1790   # fallback
1791   $x->bdiv($self->bpow($n,$y, @r), @r);
1792   $x;
1793   }
1794
1795 sub band 
1796   {
1797   #(BINT or num_str, BINT or num_str) return BINT
1798   # compute x & y
1799  
1800   # set up parameters
1801   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1802   # objectify is costly, so avoid it
1803   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1804     {
1805     ($self,$x,$y,@r) = objectify(2,@_);
1806     }
1807   
1808   return $x if $x->modify('band');
1809
1810   $r[3] = $y;                           # no push!
1811   local $Math::BigInt::upgrade = undef;
1812
1813   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1814   return $x->bzero(@r) if $y->is_zero() || $x->is_zero();
1815
1816   my $sign = 0;                                 # sign of result
1817   $sign = 1 if ($x->{sign} eq '-') && ($y->{sign} eq '-');
1818   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1819   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1820   
1821   if ($CALC->can('_and') && $sx == 1 && $sy == 1)
1822     {
1823     $x->{value} = $CALC->_and($x->{value},$y->{value});
1824     return $x->round(@r);
1825     }
1826
1827   my $m = $self->bone(); my ($xr,$yr);
1828   my $x10000 = $self->new (0x1000);
1829   my $y1 = copy(ref($x),$y);                    # make copy
1830   $y1->babs();                                  # and positive
1831   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1832   use integer;                                  # need this for negative bools
1833   while (!$x1->is_zero() && !$y1->is_zero())
1834     {
1835     ($x1, $xr) = bdiv($x1, $x10000);
1836     ($y1, $yr) = bdiv($y1, $x10000);
1837     # make both op's numbers!
1838     $x->badd( bmul( $class->new(
1839        abs($sx*int($xr->numify()) & $sy*int($yr->numify()))), 
1840       $m));
1841     $m->bmul($x10000);
1842     }
1843   $x->bneg() if $sign;
1844   $x->round(@r);
1845   }
1846
1847 sub bior 
1848   {
1849   #(BINT or num_str, BINT or num_str) return BINT
1850   # compute x | y
1851   
1852   # set up parameters
1853   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1854   # objectify is costly, so avoid it
1855   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1856     {
1857     ($self,$x,$y,@r) = objectify(2,@_);
1858     }
1859
1860   return $x if $x->modify('bior');
1861   $r[3] = $y;                           # no push!
1862
1863   local $Math::BigInt::upgrade = undef;
1864
1865   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1866   return $x->round(@r) if $y->is_zero();
1867
1868   my $sign = 0;                                 # sign of result
1869   $sign = 1 if ($x->{sign} eq '-') || ($y->{sign} eq '-');
1870   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1871   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1872
1873   # don't use lib for negative values
1874   if ($CALC->can('_or') && $sx == 1 && $sy == 1)
1875     {
1876     $x->{value} = $CALC->_or($x->{value},$y->{value});
1877     return $x->round(@r);
1878     }
1879
1880   my $m = $self->bone(); my ($xr,$yr);
1881   my $x10000 = $self->new(0x10000);
1882   my $y1 = copy(ref($x),$y);                    # make copy
1883   $y1->babs();                                  # and positive
1884   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1885   use integer;                                  # need this for negative bools
1886   while (!$x1->is_zero() || !$y1->is_zero())
1887     {
1888     ($x1, $xr) = bdiv($x1,$x10000);
1889     ($y1, $yr) = bdiv($y1,$x10000);
1890     # make both op's numbers!
1891     $x->badd( bmul( $class->new(
1892        abs($sx*int($xr->numify()) | $sy*int($yr->numify()))), 
1893       $m));
1894     $m->bmul($x10000);
1895     }
1896   $x->bneg() if $sign;
1897   $x->round(@r);
1898   }
1899
1900 sub bxor 
1901   {
1902   #(BINT or num_str, BINT or num_str) return BINT
1903   # compute x ^ y
1904   
1905   # set up parameters
1906   my ($self,$x,$y,@r) = (ref($_[0]),@_);
1907   # objectify is costly, so avoid it
1908   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
1909     {
1910     ($self,$x,$y,@r) = objectify(2,@_);
1911     }
1912
1913   return $x if $x->modify('bxor');
1914   $r[3] = $y;                           # no push!
1915
1916   local $Math::BigInt::upgrade = undef;
1917
1918   return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/);
1919   return $x->round(@r) if $y->is_zero();
1920   
1921   my $sign = 0;                                 # sign of result
1922   $sign = 1 if $x->{sign} ne $y->{sign};
1923   my $sx = 1; $sx = -1 if $x->{sign} eq '-';
1924   my $sy = 1; $sy = -1 if $y->{sign} eq '-';
1925
1926   # don't use lib for negative values
1927   if ($CALC->can('_xor') && $sx == 1 && $sy == 1)
1928     {
1929     $x->{value} = $CALC->_xor($x->{value},$y->{value});
1930     return $x->round(@r);
1931     }
1932
1933   my $m = $self->bone(); my ($xr,$yr);
1934   my $x10000 = $self->new(0x10000);
1935   my $y1 = copy(ref($x),$y);                    # make copy
1936   $y1->babs();                                  # and positive
1937   my $x1 = $x->copy()->babs(); $x->bzero();     # modify x in place!
1938   use integer;                                  # need this for negative bools
1939   while (!$x1->is_zero() || !$y1->is_zero())
1940     {
1941     ($x1, $xr) = bdiv($x1, $x10000);
1942     ($y1, $yr) = bdiv($y1, $x10000);
1943     # make both op's numbers!
1944     $x->badd( bmul( $class->new(
1945        abs($sx*int($xr->numify()) ^ $sy*int($yr->numify()))), 
1946       $m));
1947     $m->bmul($x10000);
1948     }
1949   $x->bneg() if $sign;
1950   $x->round(@r);
1951   }
1952
1953 sub length
1954   {
1955   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
1956
1957   my $e = $CALC->_len($x->{value}); 
1958   return wantarray ? ($e,0) : $e;
1959   }
1960
1961 sub digit
1962   {
1963   # return the nth decimal digit, negative values count backward, 0 is right
1964   my ($self,$x,$n) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1965
1966   $CALC->_digit($x->{value},$n||0);
1967   }
1968
1969 sub _trailing_zeros
1970   {
1971   # return the amount of trailing zeros in $x
1972   my $x = shift;
1973   $x = $class->new($x) unless ref $x;
1974
1975   return 0 if $x->is_zero() || $x->is_odd() || $x->{sign} !~ /^[+-]$/;
1976
1977   return $CALC->_zeros($x->{value}) if $CALC->can('_zeros');
1978
1979   # if not: since we do not know underlying internal representation:
1980   my $es = "$x"; $es =~ /([0]*)$/;
1981   return 0 if !defined $1;      # no zeros
1982   CORE::length("$1");           # as string, not as +0!
1983   }
1984
1985 sub bsqrt
1986   {
1987   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
1988
1989   return $x if $x->modify('bsqrt');
1990
1991   return $x->bnan() if $x->{sign} ne '+';       # -x or inf or NaN => NaN
1992   return $x->bzero(@r) if $x->is_zero();                        # 0 => 0
1993   return $x->round(@r) if $x->is_one();                 # 1 => 1
1994
1995   return $upgrade->bsqrt($x,@r) if defined $upgrade;
1996
1997   if ($CALC->can('_sqrt'))
1998     {
1999     $x->{value} = $CALC->_sqrt($x->{value});
2000     return $x->round(@r);
2001     }
2002
2003   return $x->bone('+',@r) if $x < 4;                            # 2,3 => 1
2004   my $y = $x->copy();
2005   my $l = int($x->length()/2);
2006   
2007   $x->bone();                                   # keep ref($x), but modify it
2008   $x->blsft($l,10);
2009
2010   my $last = $self->bzero();
2011   my $two = $self->new(2);
2012   my $lastlast = $x+$two;
2013   while ($last != $x && $lastlast != $x)
2014     {
2015     $lastlast = $last; $last = $x; 
2016     $x += $y / $x; 
2017     $x /= $two;
2018     }
2019   $x-- if $x * $x > $y;                         # overshot?
2020   $x->round(@r);
2021   }
2022
2023 sub exponent
2024   {
2025   # return a copy of the exponent (here always 0, NaN or 1 for $m == 0)
2026   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2027  
2028   if ($x->{sign} !~ /^[+-]$/)
2029     {
2030     my $s = $x->{sign}; $s =~ s/^[+-]//;
2031     return $self->new($s);              # -inf,+inf => inf
2032     }
2033   my $e = $class->bzero();
2034   return $e->binc() if $x->is_zero();
2035   $e += $x->_trailing_zeros();
2036   $e;
2037   }
2038
2039 sub mantissa
2040   {
2041   # return the mantissa (compatible to Math::BigFloat, e.g. reduced)
2042   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2043
2044   if ($x->{sign} !~ /^[+-]$/)
2045     {
2046     return $self->new($x->{sign});              # keep + or - sign
2047     }
2048   my $m = $x->copy();
2049   # that's inefficient
2050   my $zeros = $m->_trailing_zeros();
2051   $m->brsft($zeros,10) if $zeros != 0;
2052   $m;
2053   }
2054
2055 sub parts
2056   {
2057   # return a copy of both the exponent and the mantissa
2058   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
2059
2060   return ($x->mantissa(),$x->exponent());
2061   }
2062    
2063 ##############################################################################
2064 # rounding functions
2065
2066 sub bfround
2067   {
2068   # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
2069   # $n == 0 || $n == 1 => round to integer
2070   my $x = shift; $x = $class->new($x) unless ref $x;
2071   my ($scale,$mode) = $x->_scale_p($x->precision(),$x->round_mode(),@_);
2072   return $x if !defined $scale;         # no-op
2073   return $x if $x->modify('bfround');
2074
2075   # no-op for BigInts if $n <= 0
2076   if ($scale <= 0)
2077     {
2078     $x->{_a} = undef;                           # clear an eventual set A
2079     $x->{_p} = $scale; return $x;
2080     }
2081
2082   $x->bround( $x->length()-$scale, $mode);
2083   $x->{_a} = undef;                             # bround sets {_a}
2084   $x->{_p} = $scale;                            # so correct it
2085   $x;
2086   }
2087
2088 sub _scan_for_nonzero
2089   {
2090   my $x = shift;
2091   my $pad = shift;
2092   my $xs = shift;
2093  
2094   my $len = $x->length();
2095   return 0 if $len == 1;                # '5' is trailed by invisible zeros
2096   my $follow = $pad - 1;
2097   return 0 if $follow > $len || $follow < 1;
2098
2099   # since we do not know underlying represention of $x, use decimal string
2100   #my $r = substr ($$xs,-$follow);
2101   my $r = substr ("$x",-$follow);
2102   return 1 if $r =~ /[^0]/;
2103   0;
2104   }
2105
2106 sub fround
2107   {
2108   # to make life easier for switch between MBF and MBI (autoload fxxx()
2109   # like MBF does for bxxx()?)
2110   my $x = shift;
2111   return $x->bround(@_);
2112   }
2113
2114 sub bround
2115   {
2116   # accuracy: +$n preserve $n digits from left,
2117   #           -$n preserve $n digits from right (f.i. for 0.1234 style in MBF)
2118   # no-op for $n == 0
2119   # and overwrite the rest with 0's, return normalized number
2120   # do not return $x->bnorm(), but $x
2121
2122   my $x = shift; $x = $class->new($x) unless ref $x;
2123   my ($scale,$mode) = $x->_scale_a($x->accuracy(),$x->round_mode(),@_);
2124   return $x if !defined $scale;                 # no-op
2125   return $x if $x->modify('bround');
2126   
2127   if ($x->is_zero() || $scale == 0)
2128     {
2129     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2130     return $x;
2131     }
2132   return $x if $x->{sign} !~ /^[+-]$/;          # inf, NaN
2133
2134   # we have fewer digits than we want to scale to
2135   my $len = $x->length();
2136   # scale < 0, but > -len (not >=!)
2137   if (($scale < 0 && $scale < -$len-1) || ($scale >= $len))
2138     {
2139     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2
2140     return $x; 
2141     }
2142    
2143   # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6
2144   my ($pad,$digit_round,$digit_after);
2145   $pad = $len - $scale;
2146   $pad = abs($scale-1) if $scale < 0;
2147
2148   # do not use digit(), it is costly for binary => decimal
2149
2150   my $xs = $CALC->_str($x->{value});
2151   my $pl = -$pad-1;
2152  
2153   # pad:   123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4
2154   # pad+1: 123: 0 => 0,  at 1 => -1, at 2 => -2, at 3 => -3
2155   $digit_round = '0'; $digit_round = substr($$xs,$pl,1) if $pad <= $len;
2156   $pl++; $pl ++ if $pad >= $len;
2157   $digit_after = '0'; $digit_after = substr($$xs,$pl,1) if $pad > 0;
2158
2159   # in case of 01234 we round down, for 6789 up, and only in case 5 we look
2160   # closer at the remaining digits of the original $x, remember decision
2161   my $round_up = 1;                                     # default round up
2162   $round_up -- if
2163     ($mode eq 'trunc')                          ||      # trunc by round down
2164     ($digit_after =~ /[01234]/)                 ||      # round down anyway,
2165                                                         # 6789 => round up
2166     ($digit_after eq '5')                       &&      # not 5000...0000
2167     ($x->_scan_for_nonzero($pad,$xs) == 0)              &&
2168     (
2169      ($mode eq 'even') && ($digit_round =~ /[24680]/) ||
2170      ($mode eq 'odd')  && ($digit_round =~ /[13579]/) ||
2171      ($mode eq '+inf') && ($x->{sign} eq '-')   ||
2172      ($mode eq '-inf') && ($x->{sign} eq '+')   ||
2173      ($mode eq 'zero')          # round down if zero, sign adjusted below
2174     );
2175   my $put_back = 0;                                     # not yet modified
2176         
2177   if (($pad > 0) && ($pad <= $len))
2178     {
2179     substr($$xs,-$pad,$pad) = '0' x $pad;
2180     $put_back = 1;
2181     }
2182   elsif ($pad > $len)
2183     {
2184     $x->bzero();                                        # round to '0'
2185     }
2186
2187   if ($round_up)                                        # what gave test above?
2188     {
2189     $put_back = 1;
2190     $pad = $len, $$xs = '0'x$pad if $scale < 0;         # tlr: whack 0.51=>1.0  
2191
2192     # we modify directly the string variant instead of creating a number and
2193     # adding it, since that is faster (we already have the string)
2194     my $c = 0; $pad ++;                         # for $pad == $len case
2195     while ($pad <= $len)
2196       {
2197       $c = substr($$xs,-$pad,1) + 1; $c = '0' if $c eq '10';
2198       substr($$xs,-$pad,1) = $c; $pad++;
2199       last if $c != 0;                          # no overflow => early out
2200       }
2201     $$xs = '1'.$$xs if $c == 0;
2202
2203     }
2204   $x->{value} = $CALC->_new($xs) if $put_back == 1;     # put back in if needed
2205
2206   $x->{_a} = $scale if $scale >= 0;
2207   if ($scale < 0)
2208     {
2209     $x->{_a} = $len+$scale;
2210     $x->{_a} = 0 if $scale < -$len;
2211     }
2212   $x;
2213   }
2214
2215 sub bfloor
2216   {
2217   # return integer less or equal then number, since it is already integer,
2218   # always returns $self
2219   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2220
2221   $x->round(@r);
2222   }
2223
2224 sub bceil
2225   {
2226   # return integer greater or equal then number, since it is already integer,
2227   # always returns $self
2228   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
2229
2230   $x->round(@r);
2231   }
2232
2233 ##############################################################################
2234 # private stuff (internal use only)
2235
2236 sub __one
2237   {
2238   # internal speedup, set argument to 1, or create a +/- 1
2239   my $self = shift;
2240   my $x = $self->bone(); # $x->{value} = $CALC->_one();
2241   $x->{sign} = shift || '+';
2242   $x;
2243   }
2244
2245 sub _swap
2246   {
2247   # Overload will swap params if first one is no object ref so that the first
2248   # one is always an object ref. In this case, third param is true.
2249   # This routine is to overcome the effect of scalar,$object creating an object
2250   # of the class of this package, instead of the second param $object. This
2251   # happens inside overload, when the overload section of this package is
2252   # inherited by sub classes.
2253   # For overload cases (and this is used only there), we need to preserve the
2254   # args, hence the copy().
2255   # You can override this method in a subclass, the overload section will call
2256   # $object->_swap() to make sure it arrives at the proper subclass, with some
2257   # exceptions like '+' and '-'. To make '+' and '-' work, you also need to
2258   # specify your own overload for them.
2259
2260   # object, (object|scalar) => preserve first and make copy
2261   # scalar, object          => swapped, re-swap and create new from first
2262   #                            (using class of second object, not $class!!)
2263   my $self = shift;                     # for override in subclass
2264   if ($_[2])
2265     {
2266     my $c = ref ($_[0]) || $class;      # fallback $class should not happen
2267     return ( $c->new($_[1]), $_[0] );
2268     }
2269   return ( $_[0]->copy(), $_[1] );
2270   }
2271
2272 sub objectify
2273   {
2274   # check for strings, if yes, return objects instead
2275  
2276   # the first argument is number of args objectify() should look at it will
2277   # return $count+1 elements, the first will be a classname. This is because
2278   # overloaded '""' calls bstr($object,undef,undef) and this would result in
2279   # useless objects beeing created and thrown away. So we cannot simple loop
2280   # over @_. If the given count is 0, all arguments will be used.
2281  
2282   # If the second arg is a ref, use it as class.
2283   # If not, try to use it as classname, unless undef, then use $class 
2284   # (aka Math::BigInt). The latter shouldn't happen,though.
2285
2286   # caller:                        gives us:
2287   # $x->badd(1);                => ref x, scalar y
2288   # Class->badd(1,2);           => classname x (scalar), scalar x, scalar y
2289   # Class->badd( Class->(1),2); => classname x (scalar), ref x, scalar y
2290   # Math::BigInt::badd(1,2);    => scalar x, scalar y
2291   # In the last case we check number of arguments to turn it silently into
2292   # $class,1,2. (We can not take '1' as class ;o)
2293   # badd($class,1) is not supported (it should, eventually, try to add undef)
2294   # currently it tries 'Math::BigInt' + 1, which will not work.
2295
2296   # some shortcut for the common cases
2297   # $x->unary_op();
2298   return (ref($_[1]),$_[1]) if (@_ == 2) && ($_[0]||0 == 1) && ref($_[1]);
2299
2300   my $count = abs(shift || 0);
2301   
2302   my (@a,$k,$d);                # resulting array, temp, and downgrade 
2303   if (ref $_[0])
2304     {
2305     # okay, got object as first
2306     $a[0] = ref $_[0];
2307     }
2308   else
2309     {
2310     # nope, got 1,2 (Class->xxx(1) => Class,1 and not supported)
2311     $a[0] = $class;
2312     $a[0] = shift if $_[0] =~ /^[A-Z].*::/;     # classname as first?
2313     }
2314
2315   no strict 'refs';
2316   # disable downgrading, because Math::BigFLoat->foo('1.0','2.0') needs floats
2317   if (defined ${"$a[0]::downgrade"})
2318     {
2319     $d = ${"$a[0]::downgrade"};
2320     ${"$a[0]::downgrade"} = undef;
2321     }
2322
2323   my $up = ${"$a[0]::upgrade"};
2324   # print "Now in objectify, my class is today $a[0]\n";
2325   if ($count == 0)
2326     {
2327     while (@_)
2328       {
2329       $k = shift;
2330       if (!ref($k))
2331         {
2332         $k = $a[0]->new($k);
2333         }
2334       elsif (!defined $up && ref($k) ne $a[0])
2335         {
2336         # foreign object, try to convert to integer
2337         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2338         }
2339       push @a,$k;
2340       }
2341     }
2342   else
2343     {
2344     while ($count > 0)
2345       {
2346       $count--; 
2347       $k = shift; 
2348       if (!ref($k))
2349         {
2350         $k = $a[0]->new($k);
2351         }
2352       elsif (!defined $up && ref($k) ne $a[0])
2353         {
2354         # foreign object, try to convert to integer
2355         $k->can('as_number') ?  $k = $k->as_number() : $k = $a[0]->new($k);
2356         }
2357       push @a,$k;
2358       }
2359     push @a,@_;         # return other params, too
2360     }
2361   die "$class objectify needs list context" unless wantarray;
2362   ${"$a[0]::downgrade"} = $d;
2363   @a;
2364   }
2365
2366 sub import 
2367   {
2368   my $self = shift;
2369
2370   $IMPORT++;
2371   my @a; my $l = scalar @_;
2372   for ( my $i = 0; $i < $l ; $i++ )
2373     {
2374     if ($_[$i] eq ':constant')
2375       {
2376       # this causes overlord er load to step in
2377       overload::constant integer => sub { $self->new(shift) };
2378       overload::constant binary => sub { $self->new(shift) };
2379       }
2380     elsif ($_[$i] eq 'upgrade')
2381       {
2382       # this causes upgrading
2383       $upgrade = $_[$i+1];              # or undef to disable
2384       $i++;
2385       }
2386     elsif ($_[$i] =~ /^lib$/i)
2387       {
2388       # this causes a different low lib to take care...
2389       $CALC = $_[$i+1] || '';
2390       $i++;
2391       }
2392     else
2393       {
2394       push @a, $_[$i];
2395       }
2396     }
2397   # any non :constant stuff is handled by our parent, Exporter
2398   # even if @_ is empty, to give it a chance 
2399   $self->SUPER::import(@a);                     # need it for subclasses
2400   $self->export_to_level(1,$self,@a);           # need it for MBF
2401
2402   # try to load core math lib
2403   my @c = split /\s*,\s*/,$CALC;
2404   push @c,'Calc';                               # if all fail, try this
2405   $CALC = '';                                   # signal error
2406   foreach my $lib (@c)
2407     {
2408     next if ($lib || '') eq '';
2409     $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i;
2410     $lib =~ s/\.pm$//;
2411     if ($] < 5.006)
2412       {
2413       # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
2414       # used in the same script, or eval inside import().
2415       my @parts = split /::/, $lib;             # Math::BigInt => Math BigInt
2416       my $file = pop @parts; $file .= '.pm';    # BigInt => BigInt.pm
2417       require File::Spec;
2418       $file = File::Spec->catfile (@parts, $file);
2419       eval { require "$file"; $lib->import( @c ); }
2420       }
2421     else
2422       {
2423       eval "use $lib qw/@c/;";
2424       }
2425     $CALC = $lib, last if $@ eq '';     # no error in loading lib?
2426     }
2427   die "Couldn't load any math lib, not even the default" if $CALC eq '';
2428   }
2429
2430 sub __from_hex
2431   {
2432   # convert a (ref to) big hex string to BigInt, return undef for error
2433   my $hs = shift;
2434
2435   my $x = Math::BigInt->bzero();
2436   
2437   # strip underscores
2438   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2439   $$hs =~ s/([0-9a-fA-F])_([0-9a-fA-F])/$1$2/g; 
2440   
2441   return $x->bnan() if $$hs !~ /^[\-\+]?0x[0-9A-Fa-f]+$/;
2442
2443   my $sign = '+'; $sign = '-' if ($$hs =~ /^-/);
2444
2445   $$hs =~ s/^[+-]//;                    # strip sign
2446   if ($CALC->can('_from_hex'))
2447     {
2448     $x->{value} = $CALC->_from_hex($hs);
2449     }
2450   else
2451     {
2452     # fallback to pure perl
2453     my $mul = Math::BigInt->bzero(); $mul++;
2454     my $x65536 = Math::BigInt->new(65536);
2455     my $len = CORE::length($$hs)-2;
2456     $len = int($len/4);                 # 4-digit parts, w/o '0x'
2457     my $val; my $i = -4;
2458     while ($len >= 0)
2459       {
2460       $val = substr($$hs,$i,4);
2461       $val =~ s/^[+-]?0x// if $len == 0;        # for last part only because
2462       $val = hex($val);                         # hex does not like wrong chars
2463       $i -= 4; $len --;
2464       $x += $mul * $val if $val != 0;
2465       $mul *= $x65536 if $len >= 0;             # skip last mul
2466       }
2467     }
2468   $x->{sign} = $sign unless $CALC->_is_zero($x->{value});       # no '-0'
2469   $x;
2470   }
2471
2472 sub __from_bin
2473   {
2474   # convert a (ref to) big binary string to BigInt, return undef for error
2475   my $bs = shift;
2476
2477   my $x = Math::BigInt->bzero();
2478   # strip underscores
2479   $$bs =~ s/([01])_([01])/$1$2/g;       
2480   $$bs =~ s/([01])_([01])/$1$2/g;       
2481   return $x->bnan() if $$bs !~ /^[+-]?0b[01]+$/;
2482
2483   my $sign = '+'; $sign = '-' if ($$bs =~ /^\-/);
2484   $$bs =~ s/^[+-]//;                            # strip sign
2485   if ($CALC->can('_from_bin'))
2486     {
2487     $x->{value} = $CALC->_from_bin($bs);
2488     }
2489   else
2490     {
2491     my $mul = Math::BigInt->bzero(); $mul++;
2492     my $x256 = Math::BigInt->new(256);
2493     my $len = CORE::length($$bs)-2;
2494     $len = int($len/8);                         # 8-digit parts, w/o '0b'
2495     my $val; my $i = -8;
2496     while ($len >= 0)
2497       {
2498       $val = substr($$bs,$i,8);
2499       $val =~ s/^[+-]?0b// if $len == 0;        # for last part only
2500       #$val = oct('0b'.$val);   # does not work on Perl prior to 5.6.0
2501       # slower:
2502       # $val = ('0' x (8-CORE::length($val))).$val if CORE::length($val) < 8;
2503       $val = ord(pack('B8',substr('00000000'.$val,-8,8)));
2504       $i -= 8; $len --;
2505       $x += $mul * $val if $val != 0;
2506       $mul *= $x256 if $len >= 0;               # skip last mul
2507       }
2508     }
2509   $x->{sign} = $sign unless $CALC->_is_zero($x->{value});       # no '-0'
2510   $x;
2511   }
2512
2513 sub _split
2514   {
2515   # (ref to num_str) return num_str
2516   # internal, take apart a string and return the pieces
2517   # strip leading/trailing whitespace, leading zeros, underscore and reject
2518   # invalid input
2519   my $x = shift;
2520
2521   # strip white space at front, also extranous leading zeros
2522   $$x =~ s/^\s*([-]?)0*([0-9])/$1$2/g;  # will not strip '  .2'
2523   $$x =~ s/^\s+//;                      # but this will                 
2524   $$x =~ s/\s+$//g;                     # strip white space at end
2525
2526   # shortcut, if nothing to split, return early
2527   if ($$x =~ /^[+-]?\d+\z/)
2528     {
2529     $$x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+';
2530     return (\$sign, $x, \'', \'', \0);
2531     }
2532
2533   # invalid starting char?
2534   return if $$x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/;
2535
2536   return __from_hex($x) if $$x =~ /^[\-\+]?0x/; # hex string
2537   return __from_bin($x) if $$x =~ /^[\-\+]?0b/; # binary string
2538   
2539   # strip underscores between digits
2540   $$x =~ s/(\d)_(\d)/$1$2/g;
2541   $$x =~ s/(\d)_(\d)/$1$2/g;            # do twice for 1_2_3
2542
2543   # some possible inputs: 
2544   # 2.1234 # 0.12        # 1          # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2 
2545   # .2     # 1_2_3.4_5_6 # 1.4E1_2_3  # 1e3 # +.2
2546
2547   return if $$x =~ /[Ee].*[Ee]/;        # more than one E => error
2548
2549   my ($m,$e) = split /[Ee]/,$$x;
2550   $e = '0' if !defined $e || $e eq "";
2551   # sign,value for exponent,mantint,mantfrac
2552   my ($es,$ev,$mis,$miv,$mfv);
2553   # valid exponent?
2554   if ($e =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2555     {
2556     $es = $1; $ev = $2;
2557     # valid mantissa?
2558     return if $m eq '.' || $m eq '';
2559     my ($mi,$mf,$last) = split /\./,$m;
2560     return if defined $last;            # last defined => 1.2.3 or others
2561     $mi = '0' if !defined $mi;
2562     $mi .= '0' if $mi =~ /^[\-\+]?$/;
2563     $mf = '0' if !defined $mf || $mf eq '';
2564     if ($mi =~ /^([+-]?)0*(\d+)$/) # strip leading zeros
2565       {
2566       $mis = $1||'+'; $miv = $2;
2567       return unless ($mf =~ /^(\d*?)0*$/);      # strip trailing zeros
2568       $mfv = $1;
2569       return (\$mis,\$miv,\$mfv,\$es,\$ev);
2570       }
2571     }
2572   return; # NaN, not a number
2573   }
2574
2575 sub as_number
2576   {
2577   # an object might be asked to return itself as bigint on certain overloaded
2578   # operations, this does exactly this, so that sub classes can simple inherit
2579   # it or override with their own integer conversion routine
2580   my $self = shift;
2581
2582   $self->copy();
2583   }
2584
2585 sub as_hex
2586   {
2587   # return as hex string, with prefixed 0x
2588   my $x = shift; $x = $class->new($x) if !ref($x);
2589
2590   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2591   return '0x0' if $x->is_zero();
2592
2593   my $es = ''; my $s = '';
2594   $s = $x->{sign} if $x->{sign} eq '-';
2595   if ($CALC->can('_as_hex'))
2596     {
2597     $es = ${$CALC->_as_hex($x->{value})};
2598     }
2599   else
2600     {
2601     my $x1 = $x->copy()->babs(); my ($xr,$x10000,$h);
2602     if ($] >= 5.006)
2603       {
2604       $x10000 = Math::BigInt->new (0x10000); $h = 'h4';
2605       }
2606     else
2607       {
2608       $x10000 = Math::BigInt->new (0x1000); $h = 'h3';
2609       }
2610     while (!$x1->is_zero())
2611       {
2612       ($x1, $xr) = bdiv($x1,$x10000);
2613       $es .= unpack($h,pack('v',$xr->numify()));
2614       }
2615     $es = reverse $es;
2616     $es =~ s/^[0]+//;   # strip leading zeros
2617     $s .= '0x';
2618     }
2619   $s . $es;
2620   }
2621
2622 sub as_bin
2623   {
2624   # return as binary string, with prefixed 0b
2625   my $x = shift; $x = $class->new($x) if !ref($x);
2626
2627   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
2628   return '0b0' if $x->is_zero();
2629
2630   my $es = ''; my $s = '';
2631   $s = $x->{sign} if $x->{sign} eq '-';
2632   if ($CALC->can('_as_bin'))
2633     {
2634     $es = ${$CALC->_as_bin($x->{value})};
2635     }
2636   else
2637     {
2638     my $x1 = $x->copy()->babs(); my ($xr,$x10000,$b);
2639     if ($] >= 5.006)
2640       {
2641       $x10000 = Math::BigInt->new (0x10000); $b = 'b16';
2642       }
2643     else
2644       {
2645       $x10000 = Math::BigInt->new (0x1000); $b = 'b12';
2646       }
2647     while (!$x1->is_zero())
2648       {
2649       ($x1, $xr) = bdiv($x1,$x10000);
2650       $es .= unpack($b,pack('v',$xr->numify()));
2651       }
2652     $es = reverse $es; 
2653     $es =~ s/^[0]+//;   # strip leading zeros
2654     $s .= '0b';
2655     }
2656   $s . $es;
2657   }
2658
2659 ##############################################################################
2660 # internal calculation routines (others are in Math::BigInt::Calc etc)
2661
2662 sub __lcm 
2663   { 
2664   # (BINT or num_str, BINT or num_str) return BINT
2665   # does modify first argument
2666   # LCM
2667  
2668   my $x = shift; my $ty = shift;
2669   return $x->bnan() if ($x->{sign} eq $nan) || ($ty->{sign} eq $nan);
2670   return $x * $ty / bgcd($x,$ty);
2671   }
2672
2673 sub __gcd
2674   { 
2675   # (BINT or num_str, BINT or num_str) return BINT
2676   # does modify both arguments
2677   # GCD -- Euclids algorithm E, Knuth Vol 2 pg 296
2678   my ($x,$ty) = @_;
2679
2680   return $x->bnan() if $x->{sign} !~ /^[+-]$/ || $ty->{sign} !~ /^[+-]$/;
2681
2682   while (!$ty->is_zero())
2683     {
2684     ($x, $ty) = ($ty,bmod($x,$ty));
2685     }
2686   $x;
2687   }
2688
2689 ###############################################################################
2690 # this method return 0 if the object can be modified, or 1 for not
2691 # We use a fast use constant statement here, to avoid costly calls. Subclasses
2692 # may override it with special code (f.i. Math::BigInt::Constant does so)
2693
2694 sub modify () { 0; }
2695
2696 1;
2697 __END__
2698
2699 =head1 NAME
2700
2701 Math::BigInt - Arbitrary size integer math package
2702
2703 =head1 SYNOPSIS
2704
2705   use Math::BigInt;
2706
2707   # Number creation     
2708   $x = Math::BigInt->new($str);         # defaults to 0
2709   $nan  = Math::BigInt->bnan();         # create a NotANumber
2710   $zero = Math::BigInt->bzero();        # create a +0
2711   $inf = Math::BigInt->binf();          # create a +inf
2712   $inf = Math::BigInt->binf('-');       # create a -inf
2713   $one = Math::BigInt->bone();          # create a +1
2714   $one = Math::BigInt->bone('-');       # create a -1
2715
2716   # Testing
2717   $x->is_zero();                # true if arg is +0
2718   $x->is_nan();                 # true if arg is NaN
2719   $x->is_one();                 # true if arg is +1
2720   $x->is_one('-');              # true if arg is -1
2721   $x->is_odd();                 # true if odd, false for even
2722   $x->is_even();                # true if even, false for odd
2723   $x->is_positive();            # true if >= 0
2724   $x->is_negative();            # true if <  0
2725   $x->is_inf(sign);             # true if +inf, or -inf (sign is default '+')
2726   $x->is_int();                 # true if $x is an integer (not a float)
2727
2728   $x->bcmp($y);                 # compare numbers (undef,<0,=0,>0)
2729   $x->bacmp($y);                # compare absolutely (undef,<0,=0,>0)
2730   $x->sign();                   # return the sign, either +,- or NaN
2731   $x->digit($n);                # return the nth digit, counting from right
2732   $x->digit(-$n);               # return the nth digit, counting from left
2733
2734   # The following all modify their first argument:
2735
2736   # set 
2737   $x->bzero();                  # set $x to 0
2738   $x->bnan();                   # set $x to NaN
2739   $x->bone();                   # set $x to +1
2740   $x->bone('-');                # set $x to -1
2741   $x->binf();                   # set $x to inf
2742   $x->binf('-');                # set $x to -inf
2743
2744   $x->bneg();                   # negation
2745   $x->babs();                   # absolute value
2746   $x->bnorm();                  # normalize (no-op)
2747   $x->bnot();                   # two's complement (bit wise not)
2748   $x->binc();                   # increment x by 1
2749   $x->bdec();                   # decrement x by 1
2750   
2751   $x->badd($y);                 # addition (add $y to $x)
2752   $x->bsub($y);                 # subtraction (subtract $y from $x)
2753   $x->bmul($y);                 # multiplication (multiply $x by $y)
2754   $x->bdiv($y);                 # divide, set $x to quotient
2755                                 # return (quo,rem) or quo if scalar
2756
2757   $x->bmod($y);                 # modulus (x % y)
2758   $x->bmodpow($exp,$mod);       # modular exponentation (($num**$exp) % $mod))
2759   $x->bmodinv($mod);            # the inverse of $x in the given modulus $mod
2760
2761   $x->bpow($y);                 # power of arguments (x ** y)
2762   $x->blsft($y);                # left shift
2763   $x->brsft($y);                # right shift 
2764   $x->blsft($y,$n);             # left shift, by base $n (like 10)
2765   $x->brsft($y,$n);             # right shift, by base $n (like 10)
2766   
2767   $x->band($y);                 # bitwise and
2768   $x->bior($y);                 # bitwise inclusive or
2769   $x->bxor($y);                 # bitwise exclusive or
2770   $x->bnot();                   # bitwise not (two's complement)
2771
2772   $x->bsqrt();                  # calculate square-root
2773   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
2774
2775   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
2776   $x->bround($N);               # accuracy: preserve $N digits
2777   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
2778
2779   # The following do not modify their arguments in BigInt, but do in BigFloat:
2780   $x->bfloor();                 # return integer less or equal than $x
2781   $x->bceil();                  # return integer greater or equal than $x
2782   
2783   # The following do not modify their arguments:
2784
2785   bgcd(@values);                # greatest common divisor (no OO style)
2786   blcm(@values);                # lowest common multiplicator (no OO style)
2787  
2788   $x->length();                 # return number of digits in number
2789   ($x,$f) = $x->length();       # length of number and length of fraction part,
2790                                 # latter is always 0 digits long for BigInt's
2791
2792   $x->exponent();               # return exponent as BigInt
2793   $x->mantissa();               # return (signed) mantissa as BigInt
2794   $x->parts();                  # return (mantissa,exponent) as BigInt
2795   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
2796   $x->as_number();              # return as BigInt (in BigInt: same as copy())
2797   
2798   # conversation to string 
2799   $x->bstr();                   # normalized string
2800   $x->bsstr();                  # normalized string in scientific notation
2801   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
2802   $x->as_bin();                 # as signed binary string with prefixed 0b
2803   
2804   Math::BigInt->config();       # return hash containing configuration/version
2805
2806   # precision and accuracy (see section about rounding for more)
2807   $x->precision();              # return P of $x (or global, if P of $x undef)
2808   $x->precision($n);            # set P of $x to $n
2809   $x->accuracy();               # return A of $x (or global, if A of $x undef)
2810   $x->accuracy($n);             # set A $x to $n
2811
2812   Math::BigInt->precision();    # get/set global P for all BigInt objects
2813   Math::BigInt->accuracy();     # get/set global A for all BigInt objects
2814
2815 =head1 DESCRIPTION
2816
2817 All operators (inlcuding basic math operations) are overloaded if you
2818 declare your big integers as
2819
2820   $i = new Math::BigInt '123_456_789_123_456_789';
2821
2822 Operations with overloaded operators preserve the arguments which is
2823 exactly what you expect.
2824
2825 =over 2
2826
2827 =item Canonical notation
2828
2829 Big integer values are strings of the form C</^[+-]\d+$/> with leading
2830 zeros suppressed.
2831
2832    '-0'                            canonical value '-0', normalized '0'
2833    '   -123_123_123'               canonical value '-123123123'
2834    '1_23_456_7890'                 canonical value '1234567890'
2835
2836 =item Input
2837
2838 Input values to these routines may be either Math::BigInt objects or
2839 strings of the form C</^[+-]?[\d]+\.?[\d]*E?[+-]?[\d]*$/>.
2840
2841 You can include one underscore between any two digits. The input string may
2842 have leading and trailing whitespace, which will be ignored. In later
2843 versions, a more strict (no whitespace at all) or more lax (whitespace
2844 allowed everywhere) input checking will also be possible.
2845
2846 This means integer values like 1.01E2 or even 1000E-2 are also accepted.
2847 Non integer values result in NaN.
2848
2849 Math::BigInt::new() defaults to 0, while Math::BigInt::new('') results
2850 in 'NaN'.
2851
2852 bnorm() on a BigInt object is now effectively a no-op, since the numbers 
2853 are always stored in normalized form. On a string, it creates a BigInt 
2854 object.
2855
2856 =item Output
2857
2858 Output values are BigInt objects (normalized), except for bstr(), which
2859 returns a string in normalized form.
2860 Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
2861 C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
2862 return either undef, <0, 0 or >0 and are suited for sort.
2863
2864 =back
2865
2866 =head1 METHODS
2867
2868 Each of the methods below accepts three additional parameters. These arguments
2869 $A, $P and $R are accuracy, precision and round_mode. Please see more in the
2870 section about ACCURACY and ROUNDIND.
2871
2872 =head2 config
2873
2874         use Data::Dumper;
2875
2876         print Dumper ( Math::BigInt->config() );
2877
2878 Returns a hash containing the configuration, e.g. the version number, lib
2879 loaded etc.
2880
2881 =head2 accuracy
2882
2883         $x->accuracy(5);                # local for $x
2884         $class->accuracy(5);            # global for all members of $class
2885
2886 Set or get the global or local accuracy, aka how many significant digits the
2887 results have. Please see the section about L<ACCURACY AND PRECISION> for
2888 further details.
2889
2890 Value must be greater than zero. Pass an undef value to disable it:
2891
2892         $x->accuracy(undef);
2893         Math::BigInt->accuracy(undef);
2894
2895 Returns the current accuracy. For C<$x->accuracy()> it will return either the
2896 local accuracy, or if not defined, the global. This means the return value
2897 represents the accuracy that will be in effect for $x:
2898
2899         $y = Math::BigInt->new(1234567);        # unrounded
2900         print Math::BigInt->accuracy(4),"\n";   # set 4, print 4
2901         $x = Math::BigInt->new(123456);         # will be automatically rounded
2902         print "$x $y\n";                        # '123500 1234567'
2903         print $x->accuracy(),"\n";              # will be 4
2904         print $y->accuracy(),"\n";              # also 4, since global is 4
2905         print Math::BigInt->accuracy(5),"\n";   # set to 5, print 5
2906         print $x->accuracy(),"\n";              # still 4
2907         print $y->accuracy(),"\n";              # 5, since global is 5
2908
2909 =head2 brsft
2910
2911         $x->brsft($y,$n);               
2912
2913 Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and
2914 2, but others work, too.
2915
2916 Right shifting usually amounts to dividing $x by $n ** $y and truncating the
2917 result:
2918
2919
2920         $x = Math::BigInt->new(10);
2921         $x->brsft(1);                   # same as $x >> 1: 5
2922         $x = Math::BigInt->new(1234);
2923         $x->brsft(2,10);                # result 12
2924
2925 There is one exception, and that is base 2 with negative $x:
2926
2927
2928         $x = Math::BigInt->new(-5);
2929         print $x->brsft(1);
2930
2931 This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the
2932 result).
2933
2934 =head2 new
2935
2936         $x = Math::BigInt->new($str,$A,$P,$R);
2937
2938 Creates a new BigInt object from a string or another BigInt object. The
2939 input is accepted as decimal, hex (with leading '0x') or binary (with leading
2940 '0b').
2941
2942 =head2 bnan
2943
2944         $x = Math::BigInt->bnan();
2945
2946 Creates a new BigInt object representing NaN (Not A Number).
2947 If used on an object, it will set it to NaN:
2948
2949         $x->bnan();
2950
2951 =head2 bzero
2952
2953         $x = Math::BigInt->bzero();
2954
2955 Creates a new BigInt object representing zero.
2956 If used on an object, it will set it to zero:
2957
2958         $x->bzero();
2959
2960 =head2 binf
2961
2962         $x = Math::BigInt->binf($sign);
2963
2964 Creates a new BigInt object representing infinity. The optional argument is
2965 either '-' or '+', indicating whether you want infinity or minus infinity.
2966 If used on an object, it will set it to infinity:
2967
2968         $x->binf();
2969         $x->binf('-');
2970
2971 =head2 bone
2972
2973         $x = Math::BigInt->binf($sign);
2974
2975 Creates a new BigInt object representing one. The optional argument is
2976 either '-' or '+', indicating whether you want one or minus one.
2977 If used on an object, it will set it to one:
2978
2979         $x->bone();             # +1
2980         $x->bone('-');          # -1
2981
2982 =head2 is_one()/is_zero()/is_nan()/is_inf()
2983
2984   
2985         $x->is_zero();                  # true if arg is +0
2986         $x->is_nan();                   # true if arg is NaN
2987         $x->is_one();                   # true if arg is +1
2988         $x->is_one('-');                # true if arg is -1
2989         $x->is_inf();                   # true if +inf
2990         $x->is_inf('-');                # true if -inf (sign is default '+')
2991
2992 These methods all test the BigInt for beeing one specific value and return
2993 true or false depending on the input. These are faster than doing something
2994 like:
2995
2996         if ($x == 0)
2997
2998 =head2 is_positive()/is_negative()
2999         
3000         $x->is_positive();              # true if >= 0
3001         $x->is_negative();              # true if <  0
3002
3003 The methods return true if the argument is positive or negative, respectively.
3004 C<NaN> is neither positive nor negative, while C<+inf> counts as positive, and
3005 C<-inf> is negative. A C<zero> is positive.
3006
3007 These methods are only testing the sign, and not the value.
3008
3009 =head2 is_odd()/is_even()/is_int()
3010
3011         $x->is_odd();                   # true if odd, false for even
3012         $x->is_even();                  # true if even, false for odd
3013         $x->is_int();                   # true if $x is an integer
3014
3015 The return true when the argument satisfies the condition. C<NaN>, C<+inf>,
3016 C<-inf> are not integers and are neither odd nor even.
3017
3018 =head2 bcmp
3019
3020         $x->bcmp($y);
3021
3022 Compares $x with $y and takes the sign into account.
3023 Returns -1, 0, 1 or undef.
3024
3025 =head2 bacmp
3026
3027         $x->bacmp($y);
3028
3029 Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.
3030
3031 =head2 sign
3032
3033         $x->sign();
3034
3035 Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN.
3036
3037 =head2 bcmp
3038
3039   $x->digit($n);                # return the nth digit, counting from right
3040
3041 =head2 bneg
3042
3043         $x->bneg();
3044
3045 Negate the number, e.g. change the sign between '+' and '-', or between '+inf'
3046 and '-inf', respectively. Does nothing for NaN or zero.
3047
3048 =head2 babs
3049
3050         $x->babs();
3051
3052 Set the number to it's absolute value, e.g. change the sign from '-' to '+'
3053 and from '-inf' to '+inf', respectively. Does nothing for NaN or positive
3054 numbers.
3055
3056 =head2 bnorm
3057
3058   $x->bnorm();                  # normalize (no-op)
3059
3060 =head2 bnot
3061
3062   $x->bnot();                   # two's complement (bit wise not)
3063
3064 =head2 binc
3065
3066   $x->binc();                   # increment x by 1
3067
3068 =head2 bdec
3069
3070   $x->bdec();                   # decrement x by 1
3071
3072 =head2 badd
3073
3074   $x->badd($y);                 # addition (add $y to $x)
3075
3076 =head2 bsub
3077
3078   $x->bsub($y);                 # subtraction (subtract $y from $x)
3079
3080 =head2 bmul
3081
3082   $x->bmul($y);                 # multiplication (multiply $x by $y)
3083
3084 =head2 bdiv
3085
3086   $x->bdiv($y);                 # divide, set $x to quotient
3087                                 # return (quo,rem) or quo if scalar
3088
3089 =head2 bmod
3090
3091   $x->bmod($y);                 # modulus (x % y)
3092
3093 =head2 bmodinv
3094
3095   $num->bmodinv($mod);          # modular inverse
3096
3097 Returns the inverse of C<$num> in the given modulus C<$mod>.  'C<NaN>' is
3098 returned unless C<$num> is relatively prime to C<$mod>, i.e. unless
3099 C<bgcd($num, $mod)==1>.
3100
3101 =head2 bmodpow
3102
3103   $num->bmodpow($exp,$mod);     # modular exponentation ($num**$exp % $mod)
3104
3105 Returns the value of C<$num> taken to the power C<$exp> in the modulus
3106 C<$mod> using binary exponentation.  C<bmodpow> is far superior to
3107 writing
3108
3109   $num ** $exp % $mod
3110
3111 because C<bmodpow> is much faster--it reduces internal variables into
3112 the modulus whenever possible, so it operates on smaller numbers.
3113
3114 C<bmodpow> also supports negative exponents.
3115
3116   bmodpow($num, -1, $mod)
3117
3118 is exactly equivalent to
3119
3120   bmodinv($num, $mod)
3121
3122 =head2 bpow
3123
3124   $x->bpow($y);                 # power of arguments (x ** y)
3125
3126 =head2 blsft
3127
3128   $x->blsft($y);                # left shift
3129   $x->blsft($y,$n);             # left shift, by base $n (like 10)
3130
3131 =head2 brsft
3132
3133   $x->brsft($y);                # right shift 
3134   $x->brsft($y,$n);             # right shift, by base $n (like 10)
3135
3136 =head2 band
3137
3138   $x->band($y);                 # bitwise and
3139
3140 =head2 bior
3141
3142   $x->bior($y);                 # bitwise inclusive or
3143
3144 =head2 bxor
3145
3146   $x->bxor($y);                 # bitwise exclusive or
3147
3148 =head2 bnot
3149
3150   $x->bnot();                   # bitwise not (two's complement)
3151
3152 =head2 bsqrt
3153
3154   $x->bsqrt();                  # calculate square-root
3155
3156 =head2 bfac
3157
3158   $x->bfac();                   # factorial of $x (1*2*3*4*..$x)
3159
3160 =head2 round
3161
3162   $x->round($A,$P,$round_mode); # round to accuracy or precision using mode $r
3163
3164 =head2 bround
3165
3166   $x->bround($N);               # accuracy: preserve $N digits
3167
3168 =head2 bfround
3169
3170   $x->bfround($N);              # round to $Nth digit, no-op for BigInts
3171
3172 =head2 bfloor
3173
3174         $x->bfloor();                   
3175
3176 Set $x to the integer less or equal than $x. This is a no-op in BigInt, but
3177 does change $x in BigFloat.
3178
3179 =head2 bceil
3180
3181         $x->bceil();
3182
3183 Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but
3184 does change $x in BigFloat.
3185
3186 =head2 bgcd
3187
3188   bgcd(@values);                # greatest common divisor (no OO style)
3189
3190 =head2 blcm
3191
3192   blcm(@values);                # lowest common multiplicator (no OO style)
3193  
3194 head2 length
3195
3196         $x->length();
3197         ($xl,$fl) = $x->length();
3198
3199 Returns the number of digits in the decimal representation of the number.
3200 In list context, returns the length of the integer and fraction part. For
3201 BigInt's, the length of the fraction part will always be 0.
3202
3203 =head2 exponent
3204
3205         $x->exponent();
3206
3207 Return the exponent of $x as BigInt.
3208
3209 =head2 mantissa
3210
3211         $x->mantissa();
3212
3213 Return the signed mantissa of $x as BigInt.
3214
3215 =head2 parts
3216
3217   $x->parts();                  # return (mantissa,exponent) as BigInt
3218
3219 =head2 copy
3220
3221   $x->copy();                   # make a true copy of $x (unlike $y = $x;)
3222
3223 =head2 as_number
3224
3225   $x->as_number();              # return as BigInt (in BigInt: same as copy())
3226   
3227 =head2 bsrt
3228
3229   $x->bstr();                   # normalized string
3230
3231 =head2 bsstr
3232
3233   $x->bsstr();                  # normalized string in scientific notation
3234
3235 =head2 as_hex
3236
3237   $x->as_hex();                 # as signed hexadecimal string with prefixed 0x
3238
3239 =head2 as_bin
3240
3241   $x->as_bin();                 # as signed binary string with prefixed 0b
3242
3243 =head1 ACCURACY and PRECISION
3244
3245 Since version v1.33, Math::BigInt and Math::BigFloat have full support for
3246 accuracy and precision based rounding, both automatically after every
3247 operation as well as manually.
3248
3249 This section describes the accuracy/precision handling in Math::Big* as it
3250 used to be and as it is now, complete with an explanation of all terms and
3251 abbreviations.
3252
3253 Not yet implemented things (but with correct description) are marked with '!',
3254 things that need to be answered are marked with '?'.
3255
3256 In the next paragraph follows a short description of terms used here (because
3257 these may differ from terms used by others people or documentation).
3258
3259 During the rest of this document, the shortcuts A (for accuracy), P (for
3260 precision), F (fallback) and R (rounding mode) will be used.
3261
3262 =head2 Precision P
3263
3264 A fixed number of digits before (positive) or after (negative)
3265 the decimal point. For example, 123.45 has a precision of -2. 0 means an
3266 integer like 123 (or 120). A precision of 2 means two digits to the left
3267 of the decimal point are zero, so 123 with P = 1 becomes 120. Note that
3268 numbers with zeros before the decimal point may have different precisions,
3269 because 1200 can have p = 0, 1 or 2 (depending on what the inital value
3270 was). It could also have p < 0, when the digits after the decimal point
3271 are zero.
3272
3273 The string output (of floating point numbers) will be padded with zeros:
3274  
3275         Initial value   P       A       Result          String
3276         ------------------------------------------------------------
3277         1234.01         -3              1000            1000
3278         1234            -2              1200            1200
3279         1234.5          -1              1230            1230
3280         1234.001        1               1234            1234.0
3281         1234.01         0               1234            1234
3282         1234.01         2               1234.01         1234.01
3283         1234.01         5               1234.01         1234.01000
3284
3285 For BigInts, no padding occurs.
3286
3287 =head2 Accuracy A
3288
3289 Number of significant digits. Leading zeros are not counted. A
3290 number may have an accuracy greater than the non-zero digits
3291 when there are zeros in it or trailing zeros. For example, 123.456 has
3292 A of 6, 10203 has 5, 123.0506 has 7, 123.450000 has 8 and 0.000123 has 3.
3293
3294 The string output (of floating point numbers) will be padded with zeros:
3295
3296         Initial value   P       A       Result          String
3297         ------------------------------------------------------------
3298         1234.01                 3       1230            1230
3299         1234.01                 6       1234.01         1234.01
3300         1234.1                  8       1234.1          1234.1000
3301
3302 For BigInts, no padding occurs.
3303
3304 =head2 Fallback F
3305
3306 When both A and P are undefined, this is used as a fallback accuracy when
3307 dividing numbers.
3308
3309 =head2 Rounding mode R
3310
3311 When rounding a number, different 'styles' or 'kinds'
3312 of rounding are possible. (Note that random rounding, as in
3313 Math::Round, is not implemented.)
3314
3315 =over 2
3316
3317 =item 'trunc'
3318
3319 truncation invariably removes all digits following the
3320 rounding place, replacing them with zeros. Thus, 987.65 rounded
3321 to tens (P=1) becomes 980, and rounded to the fourth sigdig
3322 becomes 987.6 (A=4). 123.456 rounded to the second place after the
3323 decimal point (P=-2) becomes 123.46.
3324
3325 All other implemented styles of rounding attempt to round to the
3326 "nearest digit." If the digit D immediately to the right of the
3327 rounding place (skipping the decimal point) is greater than 5, the
3328 number is incremented at the rounding place (possibly causing a
3329 cascade of incrementation): e.g. when rounding to units, 0.9 rounds
3330 to 1, and -19.9 rounds to -20. If D < 5, the number is similarly
3331 truncated at the rounding place: e.g. when rounding to units, 0.4
3332 rounds to 0, and -19.4 rounds to -19.
3333
3334 However the results of other styles of rounding differ if the
3335 digit immediately to the right of the rounding place (skipping the
3336 decimal point) is 5 and if there are no digits, or no digits other
3337 than 0, after that 5. In such cases:
3338
3339 =item 'even'
3340
3341 rounds the digit at the rounding place to 0, 2, 4, 6, or 8
3342 if it is not already. E.g., when rounding to the first sigdig, 0.45
3343 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5.
3344
3345 =item 'odd'
3346
3347 rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if
3348 it is not already. E.g., when rounding to the first sigdig, 0.45
3349 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6.
3350
3351 =item '+inf'
3352
3353 round to plus infinity, i.e. always round up. E.g., when
3354 rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5,
3355 and 0.4501 also becomes 0.5.
3356
3357 =item '-inf'
3358
3359 round to minus infinity, i.e. always round down. E.g., when
3360 rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6,
3361 but 0.4501 becomes 0.5.
3362
3363 =item 'zero'
3364
3365 round to zero, i.e. positive numbers down, negative ones up.
3366 E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55
3367 becomes -0.5, but 0.4501 becomes 0.5.
3368
3369 =back
3370
3371 The handling of A & P in MBI/MBF (the old core code shipped with Perl
3372 versions <= 5.7.2) is like this:
3373
3374 =over 2
3375
3376 =item Precision
3377
3378   * ffround($p) is able to round to $p number of digits after the decimal
3379     point
3380   * otherwise P is unused
3381
3382 =item Accuracy (significant digits)
3383
3384   * fround($a) rounds to $a significant digits
3385   * only fdiv() and fsqrt() take A as (optional) paramater
3386     + other operations simply create the same number (fneg etc), or more (fmul)
3387       of digits
3388     + rounding/truncating is only done when explicitly calling one of fround
3389       or ffround, and never for BigInt (not implemented)
3390   * fsqrt() simply hands its accuracy argument over to fdiv.
3391   * the documentation and the comment in the code indicate two different ways
3392     on how fdiv() determines the maximum number of digits it should calculate,
3393     and the actual code does yet another thing
3394     POD:
3395       max($Math::BigFloat::div_scale,length(dividend)+length(divisor))
3396     Comment:
3397       result has at most max(scale, length(dividend), length(divisor)) digits
3398     Actual code:
3399       scale = max(scale, length(dividend)-1,length(divisor)-1);
3400       scale += length(divisior) - length(dividend);
3401     So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3).
3402     Actually, the 'difference' added to the scale is calculated from the
3403     number of "significant digits" in dividend and divisor, which is derived
3404     by looking at the length of the mantissa. Which is wrong, since it includes
3405     the + sign (oups) and actually gets 2 for '+100' and 4 for '+101'. Oups
3406     again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange
3407     assumption that 124 has 3 significant digits, while 120/7 will get you
3408     '17', not '17.1' since 120 is thought to have 2 significant digits.
3409     The rounding after the division then uses the remainder and $y to determine
3410     wether it must round up or down.
3411  ?  I have no idea which is the right way. That's why I used a slightly more
3412  ?  simple scheme and tweaked the few failing testcases to match it.
3413
3414 =back
3415
3416 This is how it works now:
3417
3418 =over 2
3419
3420 =item Setting/Accessing
3421
3422   * You can set the A global via Math::BigInt->accuracy() or
3423     Math::BigFloat->accuracy() or whatever class you are using.
3424   * You can also set P globally by using Math::SomeClass->precision() likewise.
3425   * Globals are classwide, and not inherited by subclasses.
3426   * to undefine A, use Math::SomeCLass->accuracy(undef);
3427   * to undefine P, use Math::SomeClass->precision(undef);
3428   * Setting Math::SomeClass->accuracy() clears automatically
3429     Math::SomeClass->precision(), and vice versa.
3430   * To be valid, A must be > 0, P can have any value.
3431   * If P is negative, this means round to the P'th place to the right of the
3432     decimal point; positive values mean to the left of the decimal point.
3433     P of 0 means round to integer.
3434   * to find out the current global A, take Math::SomeClass->accuracy()
3435   * to find out the current global P, take Math::SomeClass->precision()
3436   * use $x->accuracy() respective $x->precision() for the local setting of $x.
3437   * Please note that $x->accuracy() respecive $x->precision() fall back to the
3438     defined globals, when $x's A or P is not set.
3439
3440 =item Creating numbers
3441
3442   * When you create a number, you can give it's desired A or P via:
3443     $x = Math::BigInt->new($number,$A,$P);
3444   * Only one of A or P can be defined, otherwise the result is NaN
3445   * If no A or P is give ($x = Math::BigInt->new($number) form), then the
3446     globals (if set) will be used. Thus changing the global defaults later on
3447     will not change the A or P of previously created numbers (i.e., A and P of
3448     $x will be what was in effect when $x was created)
3449   * If given undef for A and P, B<no> rounding will occur, and the globals will
3450     B<not> be used. This is used by subclasses to create numbers without
3451     suffering rounding in the parent. Thus a subclass is able to have it's own
3452     globals enforced upon creation of a number by using
3453     $x = Math::BigInt->new($number,undef,undef):
3454
3455         use Math::Bigint::SomeSubclass;
3456         use Math::BigInt;
3457
3458         Math::BigInt->accuracy(2);
3459         Math::BigInt::SomeSubClass->accuracy(3);
3460         $x = Math::BigInt::SomeSubClass->new(1234);     
3461
3462     $x is now 1230, and not 1200. A subclass might choose to implement
3463     this otherwise, e.g. falling back to the parent's A and P.
3464
3465 =item Usage
3466
3467   * If A or P are enabled/defined, they are used to round the result of each
3468     operation according to the rules below
3469   * Negative P is ignored in Math::BigInt, since BigInts never have digits
3470     after the decimal point
3471   * Math::BigFloat uses Math::BigInts internally, but setting A or P inside
3472     Math::BigInt as globals should not tamper with the parts of a BigFloat.
3473     Thus a flag is used to mark all Math::BigFloat numbers as 'never round'
3474
3475 =item Precedence
3476
3477   * It only makes sense that a number has only one of A or P at a time.
3478     Since you can set/get both A and P, there is a rule that will practically
3479     enforce only A or P to be in effect at a time, even if both are set.
3480     This is called precedence.
3481   * If two objects are involved in an operation, and one of them has A in
3482     effect, and the other P, this results in an error (NaN).
3483   * A takes precendence over P (Hint: A comes before P). If A is defined, it
3484     is used, otherwise P is used. If neither of them is defined, nothing is
3485     used, i.e. the result will have as many digits as it can (with an
3486     exception for fdiv/fsqrt) and will not be rounded.
3487   * There is another setting for fdiv() (and thus for fsqrt()). If neither of
3488     A or P is defined, fdiv() will use a fallback (F) of $div_scale digits.
3489     If either the dividend's or the divisor's mantissa has more digits than
3490     the value of F, the higher value will be used instead of F.
3491     This is to limit the digits (A) of the result (just consider what would
3492     happen with unlimited A and P in the case of 1/3 :-)
3493   * fdiv will calculate (at least) 4 more digits than required (determined by
3494     A, P or F), and, if F is not used, round the result
3495     (this will still fail in the case of a result like 0.12345000000001 with A
3496     or P of 5, but this can not be helped - or can it?)
3497   * Thus you can have the math done by on Math::Big* class in three modes:
3498     + never round (this is the default):
3499       This is done by setting A and P to undef. No math operation
3500       will round the result, with fdiv() and fsqrt() as exceptions to guard
3501       against overflows. You must explicitely call bround(), bfround() or
3502       round() (the latter with parameters).
3503       Note: Once you have rounded a number, the settings will 'stick' on it
3504       and 'infect' all other numbers engaged in math operations with it, since
3505       local settings have the highest precedence. So, to get SaferRound[tm],
3506       use a copy() before rounding like this:
3507
3508         $x = Math::BigFloat->new(12.34);
3509         $y = Math::BigFloat->new(98.76);
3510         $z = $x * $y;                           # 1218.6984
3511         print $x->copy()->fround(3);            # 12.3 (but A is now 3!)
3512         $z = $x * $y;                           # still 1218.6984, without
3513                                                 # copy would have been 1210!
3514
3515     + round after each op:
3516       After each single operation (except for testing like is_zero()), the
3517       method round() is called and the result is rounded appropriately. By
3518       setting proper values for A and P, you can have all-the-same-A or
3519       all-the-same-P modes. For example, Math::Currency might set A to undef,
3520       and P to -2, globally.
3521
3522  ?Maybe an extra option that forbids local A & P settings would be in order,
3523  ?so that intermediate rounding does not 'poison' further math? 
3524
3525 =item Overriding globals
3526
3527   * you will be able to give A, P and R as an argument to all the calculation
3528     routines; the second parameter is A, the third one is P, and the fourth is
3529     R (shift right by one for binary operations like badd). P is used only if
3530     the first parameter (A) is undefined. These three parameters override the
3531     globals in the order detailed as follows, i.e. the first defined value
3532     wins:
3533     (local: per object, global: global default, parameter: argument to sub)
3534       + parameter A
3535       + parameter P
3536       + local A (if defined on both of the operands: smaller one is taken)
3537       + local P (if defined on both of the operands: bigger one is taken)
3538       + global A
3539       + global P
3540       + global F
3541   * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two
3542     arguments (A and P) instead of one
3543
3544 =item Local settings
3545
3546   * You can set A and P locally by using $x->accuracy() and $x->precision()
3547     and thus force different A and P for different objects/numbers.
3548   * Setting A or P this way immediately rounds $x to the new value.
3549   * $x->accuracy() clears $x->precision(), and vice versa.
3550
3551 =item Rounding
3552
3553   * the rounding routines will use the respective global or local settings.
3554     fround()/bround() is for accuracy rounding, while ffround()/bfround()
3555     is for precision
3556   * the two rounding functions take as the second parameter one of the
3557     following rounding modes (R):
3558     'even', 'odd', '+inf', '-inf', 'zero', 'trunc'
3559   * you can set and get the global R by using Math::SomeClass->round_mode()
3560     or by setting $Math::SomeClass::round_mode
3561   * after each operation, $result->round() is called, and the result may
3562     eventually be rounded (that is, if A or P were set either locally,
3563     globally or as parameter to the operation)
3564   * to manually round a number, call $x->round($A,$P,$round_mode);
3565     this will round the number by using the appropriate rounding function
3566     and then normalize it.
3567   * rounding modifies the local settings of the number:
3568
3569         $x = Math::BigFloat->new(123.456);
3570         $x->accuracy(5);
3571         $x->bround(4);
3572
3573     Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy()
3574     will be 4 from now on.
3575
3576 =item Default values
3577
3578   * R: 'even'
3579   * F: 40
3580   * A: undef
3581   * P: undef
3582
3583 =item Remarks
3584
3585   * The defaults are set up so that the new code gives the same results as
3586     the old code (except in a few cases on fdiv):
3587     + Both A and P are undefined and thus will not be used for rounding
3588       after each operation.
3589     + round() is thus a no-op, unless given extra parameters A and P
3590
3591 =back
3592
3593 =head1 INTERNALS
3594
3595 The actual numbers are stored as unsigned big integers (with seperate sign).
3596 You should neither care about nor depend on the internal representation; it
3597 might change without notice. Use only method calls like C<< $x->sign(); >>
3598 instead relying on the internal hash keys like in C<< $x->{sign}; >>. 
3599
3600 =head2 MATH LIBRARY
3601
3602 Math with the numbers is done (by default) by a module called
3603 Math::BigInt::Calc. This is equivalent to saying:
3604
3605         use Math::BigInt lib => 'Calc';
3606
3607 You can change this by using:
3608
3609         use Math::BigInt lib => 'BitVect';
3610
3611 The following would first try to find Math::BigInt::Foo, then
3612 Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
3613
3614         use Math::BigInt lib => 'Foo,Math::BigInt::Bar';
3615
3616 Calc.pm uses as internal format an array of elements of some decimal base
3617 (usually 1e5 or 1e7) with the least significant digit first, while BitVect.pm
3618 uses a bit vector of base 2, most significant bit first. Other modules might
3619 use even different means of representing the numbers. See the respective
3620 module documentation for further details.
3621
3622 =head2 SIGN
3623
3624 The sign is either '+', '-', 'NaN', '+inf' or '-inf' and stored seperately.
3625
3626 A sign of 'NaN' is used to represent the result when input arguments are not
3627 numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively
3628 minus infinity. You will get '+inf' when dividing a positive number by 0, and
3629 '-inf' when dividing any negative number by 0.
3630
3631 =head2 mantissa(), exponent() and parts()
3632
3633 C<mantissa()> and C<exponent()> return the said parts of the BigInt such
3634 that:
3635
3636         $m = $x->mantissa();
3637         $e = $x->exponent();
3638         $y = $m * ( 10 ** $e );
3639         print "ok\n" if $x == $y;
3640
3641 C<< ($m,$e) = $x->parts() >> is just a shortcut that gives you both of them
3642 in one go. Both the returned mantissa and exponent have a sign.
3643
3644 Currently, for BigInts C<$e> will be always 0, except for NaN, +inf and -inf,
3645 where it will be NaN; and for $x == 0, where it will be 1
3646 (to be compatible with Math::BigFloat's internal representation of a zero as
3647 C<0E1>).
3648
3649 C<$m> will always be a copy of the original number. The relation between $e
3650 and $m might change in the future, but will always be equivalent in a
3651 numerical sense, e.g. $m might get minimized.
3652
3653 =head1 EXAMPLES
3654  
3655   use Math::BigInt;
3656
3657   sub bint { Math::BigInt->new(shift); }
3658
3659   $x = Math::BigInt->bstr("1234")       # string "1234"
3660   $x = "$x";                            # same as bstr()
3661   $x = Math::BigInt->bneg("1234");      # Bigint "-1234"
3662   $x = Math::BigInt->babs("-12345");    # Bigint "12345"
3663   $x = Math::BigInt->bnorm("-0 00");    # BigInt "0"
3664   $x = bint(1) + bint(2);               # BigInt "3"
3665   $x = bint(1) + "2";                   # ditto (auto-BigIntify of "2")
3666   $x = bint(1);                         # BigInt "1"
3667   $x = $x + 5 / 2;                      # BigInt "3"
3668   $x = $x ** 3;                         # BigInt "27"
3669   $x *= 2;                              # BigInt "54"
3670   $x = Math::BigInt->new(0);            # BigInt "0"
3671   $x--;                                 # BigInt "-1"
3672   $x = Math::BigInt->badd(4,5)          # BigInt "9"
3673   print $x->bsstr();                    # 9e+0
3674
3675 Examples for rounding:
3676
3677   use Math::BigFloat;
3678   use Test;
3679
3680   $x = Math::BigFloat->new(123.4567);
3681   $y = Math::BigFloat->new(123.456789);
3682   Math::BigFloat->accuracy(4);          # no more A than 4
3683
3684   ok ($x->copy()->fround(),123.4);      # even rounding
3685   print $x->copy()->fround(),"\n";      # 123.4
3686   Math::BigFloat->round_mode('odd');    # round to odd
3687   print $x->copy()->fround(),"\n";      # 123.5
3688   Math::BigFloat->accuracy(5);          # no more A than 5
3689   Math::BigFloat->round_mode('odd');    # round to odd
3690   print $x->copy()->fround(),"\n";      # 123.46
3691   $y = $x->copy()->fround(4),"\n";      # A = 4: 123.4
3692   print "$y, ",$y->accuracy(),"\n";     # 123.4, 4
3693
3694   Math::BigFloat->accuracy(undef);      # A not important now
3695   Math::BigFloat->precision(2);         # P important
3696   print $x->copy()->bnorm(),"\n";       # 123.46
3697   print $x->copy()->fround(),"\n";      # 123.46
3698
3699 Examples for converting:
3700
3701   my $x = Math::BigInt->new('0b1'.'01' x 123);
3702   print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";
3703
3704 =head1 Autocreating constants
3705
3706 After C<use Math::BigInt ':constant'> all the B<integer> decimal, hexadecimal
3707 and binary constants in the given scope are converted to C<Math::BigInt>.
3708 This conversion happens at compile time. 
3709
3710 In particular,
3711
3712   perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'
3713
3714 prints the integer value of C<2**100>. Note that without conversion of 
3715 constants the expression 2**100 will be calculated as perl scalar.
3716
3717 Please note that strings and floating point constants are not affected,
3718 so that
3719
3720         use Math::BigInt qw/:constant/;
3721
3722         $x = 1234567890123456789012345678901234567890
3723                 + 123456789123456789;
3724         $y = '1234567890123456789012345678901234567890'
3725                 + '123456789123456789';
3726
3727 do not work. You need an explicit Math::BigInt->new() around one of the
3728 operands. You should also quote large constants to protect loss of precision:
3729
3730         use Math::Bigint;
3731
3732         $x = Math::BigInt->new('1234567889123456789123456789123456789');
3733
3734 Without the quotes Perl would convert the large number to a floating point
3735 constant at compile time and then hand the result to BigInt, which results in
3736 an truncated result or a NaN.
3737
3738 This also applies to integers that look like floating point constants:
3739
3740         use Math::BigInt ':constant';
3741
3742         print ref(123e2),"\n";
3743         print ref(123.2e2),"\n";
3744
3745 will print nothing but newlines. Use either L<bignum> or L<Math::BigFloat>
3746 to get this to work.
3747
3748 =head1 PERFORMANCE
3749
3750 Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x
3751 must be made in the second case. For long numbers, the copy can eat up to 20%
3752 of the work (in the case of addition/subtraction, less for
3753 multiplication/division). If $y is very small compared to $x, the form
3754 $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes
3755 more time then the actual addition.
3756
3757 With a technique called copy-on-write, the cost of copying with overload could
3758 be minimized or even completely avoided. A test implementation of COW did show
3759 performance gains for overloaded math, but introduced a performance loss due
3760 to a constant overhead for all other operatons.
3761
3762 The rewritten version of this module is slower on certain operations, like
3763 new(), bstr() and numify(). The reason are that it does now more work and
3764 handles more cases. The time spent in these operations is usually gained in
3765 the other operations so that programs on the average should get faster. If
3766 they don't, please contect the author.
3767
3768 Some operations may be slower for small numbers, but are significantly faster
3769 for big numbers. Other operations are now constant (O(1), like bneg(), babs()
3770 etc), instead of O(N) and thus nearly always take much less time. These
3771 optimizations were done on purpose.
3772
3773 If you find the Calc module to slow, try to install any of the replacement
3774 modules and see if they help you. 
3775
3776 =head2 Alternative math libraries
3777
3778 You can use an alternative library to drive Math::BigInt via:
3779
3780         use Math::BigInt lib => 'Module';
3781
3782 See L<MATH LIBRARY> for more information.
3783
3784 For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>.
3785
3786 =head2 SUBCLASSING
3787
3788 =head1 Subclassing Math::BigInt
3789
3790 The basic design of Math::BigInt allows simple subclasses with very little
3791 work, as long as a few simple rules are followed:
3792
3793 =over 2
3794
3795 =item *
3796
3797 The public API must remain consistent, i.e. if a sub-class is overloading
3798 addition, the sub-class must use the same name, in this case badd(). The
3799 reason for this is that Math::BigInt is optimized to call the object methods
3800 directly.
3801
3802 =item *
3803
3804 The private object hash keys like C<$x->{sign}> may not be changed, but
3805 additional keys can be added, like C<$x->{_custom}>.
3806
3807 =item *
3808
3809 Accessor functions are available for all existing object hash keys and should
3810 be used instead of directly accessing the internal hash keys. The reason for
3811 this is that Math::BigInt itself has a pluggable interface which permits it
3812 to support different storage methods.
3813
3814 =back
3815
3816 More complex sub-classes may have to replicate more of the logic internal of
3817 Math::BigInt if they need to change more basic behaviors. A subclass that
3818 needs to merely change the output only needs to overload C<bstr()>. 
3819
3820 All other object methods and overloaded functions can be directly inherited
3821 from the parent class.
3822
3823 At the very minimum, any subclass will need to provide it's own C<new()> and can
3824 store additional hash keys in the object. There are also some package globals
3825 that must be defined, e.g.:
3826
3827   # Globals
3828   $accuracy = undef;
3829   $precision = -2;       # round to 2 decimal places
3830   $round_mode = 'even';
3831   $div_scale = 40;
3832
3833 Additionally, you might want to provide the following two globals to allow
3834 auto-upgrading and auto-downgrading to work correctly:
3835
3836   $upgrade = undef;
3837   $downgrade = undef;
3838
3839 This allows Math::BigInt to correctly retrieve package globals from the 
3840 subclass, like C<$SubClass::precision>.  See t/Math/BigInt/Subclass.pm or
3841 t/Math/BigFloat/SubClass.pm completely functional subclass examples.
3842
3843 Don't forget to 
3844
3845         use overload;
3846
3847 in your subclass to automatically inherit the overloading from the parent. If
3848 you like, you can change part of the overloading, look at Math::String for an
3849 example.
3850
3851 =head1 UPGRADING
3852
3853 When used like this:
3854
3855         use Math::BigInt upgrade => 'Foo::Bar';
3856
3857 certain operations will 'upgrade' their calculation and thus the result to
3858 the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:
3859
3860         use Math::BigInt upgrade => 'Math::BigFloat';
3861
3862 As a shortcut, you can use the module C<bignum>:
3863
3864         use bignum;
3865
3866 Also good for oneliners:
3867
3868         perl -Mbignum -le 'print 2 ** 255'
3869
3870 This makes it possible to mix arguments of different classes (as in 2.5 + 2)
3871 as well es preserve accuracy (as in sqrt(3)).
3872
3873 Beware: This feature is not fully implemented yet.
3874
3875 =head2 Auto-upgrade
3876
3877 The following methods upgrade themselves unconditionally; that is if upgrade
3878 is in effect, they will always hand up their work:
3879
3880 =over 2
3881
3882 =item bsqrt()
3883
3884 =item div()
3885
3886 =item blog()
3887
3888 =back
3889
3890 Beware: This list is not complete.
3891
3892 All other methods upgrade themselves only when one (or all) of their
3893 arguments are of the class mentioned in $upgrade (This might change in later
3894 versions to a more sophisticated scheme):
3895
3896 =head1 BUGS
3897
3898 =over 2
3899
3900 =item Out of Memory!
3901
3902 Under Perl prior to 5.6.0 having an C<use Math::BigInt ':constant';> and 
3903 C<eval()> in your code will crash with "Out of memory". This is probably an
3904 overload/exporter bug. You can workaround by not having C<eval()> 
3905 and ':constant' at the same time or upgrade your Perl to a newer version.
3906
3907 =item Fails to load Calc on Perl prior 5.6.0
3908
3909 Since eval(' use ...') can not be used in conjunction with ':constant', BigInt
3910 will fall back to eval { require ... } when loading the math lib on Perls
3911 prior to 5.6.0. This simple replaces '::' with '/' and thus might fail on
3912 filesystems using a different seperator.  
3913
3914 =back
3915
3916 =head1 CAVEATS
3917
3918 Some things might not work as you expect them. Below is documented what is
3919 known to be troublesome:
3920
3921 =over 1
3922
3923 =item stringify, bstr(), bsstr() and 'cmp'
3924
3925 Both stringify and bstr() now drop the leading '+'. The old code would return
3926 '+3', the new returns '3'. This is to be consistent with Perl and to make
3927 cmp (especially with overloading) to work as you expect. It also solves
3928 problems with Test.pm, it's ok() uses 'eq' internally. 
3929
3930 Mark said, when asked about to drop the '+' altogether, or make only cmp work:
3931
3932         I agree (with the first alternative), don't add the '+' on positive
3933         numbers.  It's not as important anymore with the new internal 
3934         form for numbers.  It made doing things like abs and neg easier,
3935         but those have to be done differently now anyway.
3936
3937 So, the following examples will now work all as expected:
3938
3939         use Test;
3940         BEGIN { plan tests => 1 }
3941         use Math::BigInt;
3942
3943         my $x = new Math::BigInt 3*3;
3944         my $y = new Math::BigInt 3*3;
3945
3946         ok ($x,3*3);
3947         print "$x eq 9" if $x eq $y;
3948         print "$x eq 9" if $x eq '9';
3949         print "$x eq 9" if $x eq 3*3;
3950
3951 Additionally, the following still works:
3952         
3953         print "$x == 9" if $x == $y;
3954         print "$x == 9" if $x == 9;
3955         print "$x == 9" if $x == 3*3;
3956
3957 There is now a C<bsstr()> method to get the string in scientific notation aka
3958 C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr()
3959 for comparisation, but Perl will represent some numbers as 100 and others
3960 as 1e+308. If in doubt, convert both arguments to Math::BigInt before doing eq:
3961
3962         use Test;
3963         BEGIN { plan tests => 3 }
3964         use Math::BigInt;
3965
3966         $x = Math::BigInt->new('1e56'); $y = 1e56;
3967         ok ($x,$y);                     # will fail
3968         ok ($x->bsstr(),$y);            # okay
3969         $y = Math::BigInt->new($y);
3970         ok ($x,$y);                     # okay
3971
3972 Alternatively, simple use <=> for comparisations, that will get it always
3973 right. There is not yet a way to get a number automatically represented as
3974 a string that matches exactly the way Perl represents it.
3975
3976 =item int()
3977
3978 C<int()> will return (at least for Perl v5.7.1 and up) another BigInt, not a 
3979 Perl scalar:
3980
3981         $x = Math::BigInt->new(123);
3982         $y = int($x);                           # BigInt 123
3983         $x = Math::BigFloat->new(123.45);
3984         $y = int($x);                           # BigInt 123
3985
3986 In all Perl versions you can use C<as_number()> for the same effect:
3987
3988         $x = Math::BigFloat->new(123.45);
3989         $y = $x->as_number();                   # BigInt 123
3990
3991 This also works for other subclasses, like Math::String.
3992
3993 It is yet unlcear whether overloaded int() should return a scalar or a BigInt.
3994
3995 =item length
3996
3997 The following will probably not do what you expect:
3998
3999         $c = Math::BigInt->new(123);
4000         print $c->length(),"\n";                # prints 30
4001
4002 It prints both the number of digits in the number and in the fraction part
4003 since print calls C<length()> in list context. Use something like: 
4004         
4005         print scalar $c->length(),"\n";         # prints 3 
4006
4007 =item bdiv
4008
4009 The following will probably not do what you expect:
4010
4011         print $c->bdiv(10000),"\n";
4012
4013 It prints both quotient and remainder since print calls C<bdiv()> in list
4014 context. Also, C<bdiv()> will modify $c, so be carefull. You probably want
4015 to use
4016         
4017         print $c / 10000,"\n";
4018         print scalar $c->bdiv(10000),"\n";  # or if you want to modify $c
4019
4020 instead.
4021
4022 The quotient is always the greatest integer less than or equal to the
4023 real-valued quotient of the two operands, and the remainder (when it is
4024 nonzero) always has the same sign as the second operand; so, for
4025 example,
4026
4027           1 / 4  => ( 0, 1)
4028           1 / -4 => (-1,-3)
4029          -3 / 4  => (-1, 1)
4030          -3 / -4 => ( 0,-3)
4031         -11 / 2  => (-5,1)
4032          11 /-2  => (-5,-1)
4033
4034 As a consequence, the behavior of the operator % agrees with the
4035 behavior of Perl's built-in % operator (as documented in the perlop
4036 manpage), and the equation
4037
4038         $x == ($x / $y) * $y + ($x % $y)
4039
4040 holds true for any $x and $y, which justifies calling the two return
4041 values of bdiv() the quotient and remainder. The only exception to this rule
4042 are when $y == 0 and $x is negative, then the remainder will also be
4043 negative. See below under "infinity handling" for the reasoning behing this.
4044
4045 Perl's 'use integer;' changes the behaviour of % and / for scalars, but will
4046 not change BigInt's way to do things. This is because under 'use integer' Perl
4047 will do what the underlying C thinks is right and this is different for each
4048 system. If you need BigInt's behaving exactly like Perl's 'use integer', bug
4049 the author to implement it ;)
4050
4051 =item infinity handling
4052
4053 Here are some examples that explain the reasons why certain results occur while
4054 handling infinity:
4055
4056 The following table shows the result of the division and the remainder, so that
4057 the equation above holds true. Some "ordinary" cases are strewn in to show more
4058 clearly the reasoning:
4059
4060         A /  B  =   C,     R so that C *    B +    R =    A
4061      =========================================================
4062         5 /   8 =   0,     5         0 *    8 +    5 =    5
4063         0 /   8 =   0,     0         0 *    8 +    0 =    0
4064         0 / inf =   0,     0         0 *  inf +    0 =    0
4065         0 /-inf =   0,     0         0 * -inf +    0 =    0
4066         5 / inf =   0,     5         0 *  inf +    5 =    5
4067         5 /-inf =   0,     5         0 * -inf +    5 =    5
4068         -5/ inf =   0,    -5         0 *  inf +   -5 =   -5
4069         -5/-inf =   0,    -5         0 * -inf +   -5 =   -5
4070        inf/   5 =  inf,    0       inf *    5 +    0 =  inf
4071       -inf/   5 = -inf,    0      -inf *    5 +    0 = -inf
4072        inf/  -5 = -inf,    0      -inf *   -5 +    0 =  inf
4073       -inf/  -5 =  inf,    0       inf *   -5 +    0 = -inf
4074          5/   5 =    1,    0         1 *    5 +    0 =    5
4075         -5/  -5 =    1,    0         1 *   -5 +    0 =   -5
4076        inf/ inf =    1,    0         1 *  inf +    0 =  inf
4077       -inf/-inf =    1,    0         1 * -inf +    0 = -inf
4078        inf/-inf =   -1,    0        -1 * -inf +    0 =  inf
4079       -inf/ inf =   -1,    0         1 * -inf +    0 = -inf
4080          8/   0 =  inf,    8       inf *    0 +    8 =    8 
4081        inf/   0 =  inf,  inf       inf *    0 +  inf =  inf 
4082          0/   0 =  NaN
4083
4084 These cases below violate the "remainder has the sign of the second of the two
4085 arguments", since they wouldn't match up otherwise.
4086
4087         A /  B  =   C,     R so that C *    B +    R =    A
4088      ========================================================
4089       -inf/   0 = -inf, -inf      -inf *    0 +  inf = -inf 
4090         -8/   0 = -inf,   -8      -inf *    0 +    8 = -8 
4091
4092 =item Modifying and =
4093
4094 Beware of:
4095
4096         $x = Math::BigFloat->new(5);
4097         $y = $x;
4098
4099 It will not do what you think, e.g. making a copy of $x. Instead it just makes
4100 a second reference to the B<same> object and stores it in $y. Thus anything
4101 that modifies $x (except overloaded operators) will modify $y, and vice versa.
4102 Or in other words, C<=> is only safe if you modify your BigInts only via
4103 overloaded math. As soon as you use a method call it breaks:
4104
4105         $x->bmul(2);
4106         print "$x, $y\n";       # prints '10, 10'
4107
4108 If you want a true copy of $x, use:
4109
4110         $y = $x->copy();
4111
4112 You can also chain the calls like this, this will make first a copy and then
4113 multiply it by 2:
4114
4115         $y = $x->copy()->bmul(2);
4116
4117 See also the documentation for overload.pm regarding C<=>.
4118
4119 =item bpow
4120
4121 C<bpow()> (and the rounding functions) now modifies the first argument and
4122 returns it, unlike the old code which left it alone and only returned the
4123 result. This is to be consistent with C<badd()> etc. The first three will
4124 modify $x, the last one won't:
4125
4126         print bpow($x,$i),"\n";         # modify $x
4127         print $x->bpow($i),"\n";        # ditto
4128         print $x **= $i,"\n";           # the same
4129         print $x ** $i,"\n";            # leave $x alone 
4130
4131 The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though.
4132
4133 =item Overloading -$x
4134
4135 The following:
4136
4137         $x = -$x;
4138
4139 is slower than
4140
4141         $x->bneg();
4142
4143 since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant
4144 needs to preserve $x since it does not know that it later will get overwritten.
4145 This makes a copy of $x and takes O(N), but $x->bneg() is O(1).
4146
4147 With Copy-On-Write, this issue would be gone, but C-o-W is not implemented
4148 since it is slower for all other things.
4149
4150 =item Mixing different object types
4151
4152 In Perl you will get a floating point value if you do one of the following:
4153
4154         $float = 5.0 + 2;
4155         $float = 2 + 5.0;
4156         $float = 5 / 2;
4157
4158 With overloaded math, only the first two variants will result in a BigFloat:
4159
4160         use Math::BigInt;
4161         use Math::BigFloat;
4162         
4163         $mbf = Math::BigFloat->new(5);
4164         $mbi2 = Math::BigInteger->new(5);
4165         $mbi = Math::BigInteger->new(2);
4166
4167                                         # what actually gets called:
4168         $float = $mbf + $mbi;           # $mbf->badd()
4169         $float = $mbf / $mbi;           # $mbf->bdiv()
4170         $integer = $mbi + $mbf;         # $mbi->badd()
4171         $integer = $mbi2 / $mbi;        # $mbi2->bdiv()
4172         $integer = $mbi2 / $mbf;        # $mbi2->bdiv()
4173
4174 This is because math with overloaded operators follows the first (dominating)
4175 operand, and the operation of that is called and returns thus the result. So,
4176 Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether
4177 the result should be a Math::BigFloat or the second operant is one.
4178
4179 To get a Math::BigFloat you either need to call the operation manually,
4180 make sure the operands are already of the proper type or casted to that type
4181 via Math::BigFloat->new():
4182         
4183         $float = Math::BigFloat->new($mbi2) / $mbi;     # = 2.5
4184
4185 Beware of simple "casting" the entire expression, this would only convert
4186 the already computed result:
4187
4188         $float = Math::BigFloat->new($mbi2 / $mbi);     # = 2.0 thus wrong!
4189
4190 Beware also of the order of more complicated expressions like:
4191
4192         $integer = ($mbi2 + $mbi) / $mbf;               # int / float => int
4193         $integer = $mbi2 / Math::BigFloat->new($mbi);   # ditto
4194
4195 If in doubt, break the expression into simpler terms, or cast all operands
4196 to the desired resulting type.
4197
4198 Scalar values are a bit different, since:
4199         
4200         $float = 2 + $mbf;
4201         $float = $mbf + 2;
4202
4203 will both result in the proper type due to the way the overloaded math works.
4204
4205 This section also applies to other overloaded math packages, like Math::String.
4206
4207 One solution to you problem might be L<autoupgrading|upgrading>.
4208
4209 =item bsqrt()
4210
4211 C<bsqrt()> works only good if the result is a big integer, e.g. the square
4212 root of 144 is 12, but from 12 the square root is 3, regardless of rounding
4213 mode.
4214
4215 If you want a better approximation of the square root, then use:
4216
4217         $x = Math::BigFloat->new(12);
4218         Math::BigFloat->precision(0);
4219         Math::BigFloat->round_mode('even');
4220         print $x->copy->bsqrt(),"\n";           # 4
4221
4222         Math::BigFloat->precision(2);
4223         print $x->bsqrt(),"\n";                 # 3.46
4224         print $x->bsqrt(3),"\n";                # 3.464
4225
4226 =item brsft()
4227
4228 For negative numbers in base see also L<brsft|brsft>.
4229
4230 =back
4231
4232 =head1 LICENSE
4233
4234 This program is free software; you may redistribute it and/or modify it under
4235 the same terms as Perl itself.
4236
4237 =head1 SEE ALSO
4238
4239 L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
4240 L<Math::BigInt::Pari> and  L<Math::BigInt::GMP>.
4241
4242 The package at
4243 L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
4244 more documentation including a full version history, testcases, empty
4245 subclass files and benchmarks.
4246
4247 =head1 AUTHORS
4248
4249 Original code by Mark Biggar, overloaded interface by Ilya Zakharevich.
4250 Completely rewritten by Tels http://bloodgate.com in late 2000, 2001.
4251
4252 =cut