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