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