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