home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / BigFloat.pm < prev    next >
Encoding:
Perl POD Document  |  2004-01-13  |  84.2 KB  |  2,830 lines

  1. package Math::BigFloat;
  2.  
  3. # Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After'
  4. #
  5.  
  6. # The following hash values are internally used:
  7. #   _e: exponent (BigInt)
  8. #   _m: mantissa (absolute BigInt)
  9. # sign: +,-,+inf,-inf, or "NaN" if not a number
  10. #   _a: accuracy
  11. #   _p: precision
  12. #   _f: flags, used to signal MBI not to touch our private parts
  13.  
  14. $VERSION = '1.43';
  15. require 5.005;
  16.  
  17. require Exporter;
  18. @ISA =       qw(Exporter Math::BigInt);
  19.  
  20. use strict;
  21. # $_trap_inf and $_trap_nan are internal and should never be accessed from the outside
  22. use vars qw/$AUTOLOAD $accuracy $precision $div_scale $round_mode $rnd_mode
  23.         $upgrade $downgrade $_trap_nan $_trap_inf/;
  24. my $class = "Math::BigFloat";
  25.  
  26. use overload
  27. '<=>'    =>    sub { $_[2] ?
  28.                       ref($_[0])->bcmp($_[1],$_[0]) : 
  29.                       ref($_[0])->bcmp($_[0],$_[1])},
  30. 'int'    =>    sub { $_[0]->as_number() },        # 'trunc' to bigint
  31. ;
  32.  
  33. ##############################################################################
  34. # global constants, flags and assorted stuff
  35.  
  36. # the following are public, but their usage is not recommended. Use the
  37. # accessor methods instead.
  38.  
  39. # class constants, use Class->constant_name() to access
  40. $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'
  41. $accuracy   = undef;
  42. $precision  = undef;
  43. $div_scale  = 40;
  44.  
  45. $upgrade = undef;
  46. $downgrade = undef;
  47. my $MBI = 'Math::BigInt'; # the package we are using for our private parts
  48.               # changable by use Math::BigFloat with => 'package'
  49.  
  50. # the following are private and not to be used from the outside:
  51.  
  52. sub MB_NEVER_ROUND () { 0x0001; }
  53.  
  54. # are NaNs ok? (otherwise it dies when encountering an NaN) set w/ config()
  55. $_trap_nan = 0;
  56. # the same for infs
  57. $_trap_inf = 0;
  58.  
  59. # constant for easier life
  60. my $nan = 'NaN'; 
  61.  
  62. my $IMPORT = 0;                         # was import() called yet?
  63.                                         # used to make require work
  64.  
  65. # some digits of accuracy for blog(undef,10); which we use in blog() for speed
  66. my $LOG_10 = 
  67.  '2.3025850929940456840179914546843642076011014886287729760333279009675726097';
  68. my $LOG_10_A = length($LOG_10)-1;
  69. # ditto for log(2)
  70. my $LOG_2 = 
  71.  '0.6931471805599453094172321214581765680755001343602552541206800094933936220';
  72. my $LOG_2_A = length($LOG_2)-1;
  73.  
  74. ##############################################################################
  75. # the old code had $rnd_mode, so we need to support it, too
  76.  
  77. sub TIESCALAR   { my ($class) = @_; bless \$round_mode, $class; }
  78. sub FETCH       { return $round_mode; }
  79. sub STORE       { $rnd_mode = $_[0]->round_mode($_[1]); }
  80.  
  81. BEGIN
  82.   {
  83.   # when someone set's $rnd_mode, we catch this and check the value to see
  84.   # whether it is valid or not. 
  85.   $rnd_mode   = 'even'; tie $rnd_mode, 'Math::BigFloat'; 
  86.   }
  87.  
  88. ##############################################################################
  89.  
  90. {
  91.   # valid method aliases for AUTOLOAD
  92.   my %methods = map { $_ => 1 }  
  93.    qw / fadd fsub fmul fdiv fround ffround fsqrt fmod fstr fsstr fpow fnorm
  94.         fint facmp fcmp fzero fnan finf finc fdec flog ffac
  95.     fceil ffloor frsft flsft fone flog froot
  96.       /;
  97.   # valid method's that can be hand-ed up (for AUTOLOAD)
  98.   my %hand_ups = map { $_ => 1 }  
  99.    qw / is_nan is_inf is_negative is_positive is_pos is_neg
  100.         accuracy precision div_scale round_mode fneg fabs fnot
  101.         objectify upgrade downgrade
  102.     bone binf bnan bzero
  103.       /;
  104.  
  105.   sub method_alias { exists $methods{$_[0]||''}; } 
  106.   sub method_hand_up { exists $hand_ups{$_[0]||''}; } 
  107. }
  108.  
  109. ##############################################################################
  110. # constructors
  111.  
  112. sub new 
  113.   {
  114.   # create a new BigFloat object from a string or another bigfloat object. 
  115.   # _e: exponent
  116.   # _m: mantissa
  117.   # sign  => sign (+/-), or "NaN"
  118.  
  119.   my ($class,$wanted,@r) = @_;
  120.  
  121.   # avoid numify-calls by not using || on $wanted!
  122.   return $class->bzero() if !defined $wanted;    # default to 0
  123.   return $wanted->copy() if UNIVERSAL::isa($wanted,'Math::BigFloat');
  124.  
  125.   $class->import() if $IMPORT == 0;             # make require work
  126.  
  127.   my $self = {}; bless $self, $class;
  128.   # shortcut for bigints and its subclasses
  129.   if ((ref($wanted)) && (ref($wanted) ne $class))
  130.     {
  131.     $self->{_m} = $wanted->as_number();        # get us a bigint copy
  132.     $self->{_e} = $MBI->bzero();
  133.     $self->{_m}->babs();
  134.     $self->{sign} = $wanted->sign();
  135.     return $self->bnorm();
  136.     }
  137.   # got string
  138.   # handle '+inf', '-inf' first
  139.   if ($wanted =~ /^[+-]?inf$/)
  140.     {
  141.     return $downgrade->new($wanted) if $downgrade;
  142.  
  143.     $self->{_e} = $MBI->bzero();
  144.     $self->{_m} = $MBI->bzero();
  145.     $self->{sign} = $wanted;
  146.     $self->{sign} = '+inf' if $self->{sign} eq 'inf';
  147.     return $self->bnorm();
  148.     }
  149.   #print "new string '$wanted'\n";
  150.  
  151.   my ($mis,$miv,$mfv,$es,$ev) = Math::BigInt::_split(\$wanted);
  152.   if (!ref $mis)
  153.     {
  154.     if ($_trap_nan)
  155.       {
  156.       require Carp;
  157.       Carp::croak ("$wanted is not a number initialized to $class");
  158.       }
  159.     
  160.     return $downgrade->bnan() if $downgrade;
  161.     
  162.     $self->{_e} = $MBI->bzero();
  163.     $self->{_m} = $MBI->bzero();
  164.     $self->{sign} = $nan;
  165.     }
  166.   else
  167.     {
  168.     # make integer from mantissa by adjusting exp, then convert to bigint
  169.     # undef,undef to signal MBI that we don't need no bloody rounding
  170.     $self->{_e} = $MBI->new("$$es$$ev",undef,undef);    # exponent
  171.     $self->{_m} = $MBI->new("$$miv$$mfv",undef,undef);     # create mant.
  172.  
  173.     # this is to prevent automatically rounding when MBI's globals are set
  174.     $self->{_m}->{_f} = MB_NEVER_ROUND;
  175.     $self->{_e}->{_f} = MB_NEVER_ROUND;
  176.  
  177.     # 3.123E0 = 3123E-3, and 3.123E-2 => 3123E-5
  178.     $self->{_e}->bsub( $MBI->new(CORE::length($$mfv),undef,undef))
  179.       if CORE::length($$mfv) != 0;
  180.     $self->{sign} = $$mis;
  181.     
  182.     #print "$$miv$$mfv $$es$$ev\n";
  183.  
  184.     # we can only have trailing zeros on the mantissa of $$mfv eq ''
  185.     if (CORE::length($$mfv) == 0)
  186.       {
  187.       my $zeros = $self->{_m}->_trailing_zeros(); # correct for trailing zeros 
  188.       if ($zeros != 0)
  189.         {
  190.         $self->{_m}->brsft($zeros,10); $self->{_e}->badd($MBI->new($zeros));
  191.         }
  192.       }
  193. #    else
  194. #      {
  195.       # for something like 0Ey, set y to 1, and -0 => +0
  196.       $self->{sign} = '+', $self->{_e}->bone() if $self->{_m}->is_zero();
  197. #      }
  198.     return $self->round(@r) if !$downgrade;
  199.     }
  200.   # if downgrade, inf, NaN or integers go down
  201.  
  202.   if ($downgrade && $self->{_e}->{sign} eq '+')
  203.     {
  204.     #print "downgrading $$miv$$mfv"."E$$es$$ev";
  205.     if ($self->{_e}->is_zero())
  206.       {
  207.       $self->{_m}->{sign} = $$mis;        # negative if wanted
  208.       return $downgrade->new($self->{_m});
  209.       }
  210.     return $downgrade->new($self->bsstr()); 
  211.     }
  212.   #print "mbf new $self->{sign} $self->{_m} e $self->{_e} ",ref($self),"\n";
  213.   $self->bnorm()->round(@r);            # first normalize, then round
  214.   }
  215.  
  216. sub _bnan
  217.   {
  218.   # used by parent class bone() to initialize number to NaN
  219.   my $self = shift;
  220.   
  221.   if ($_trap_nan)
  222.     {
  223.     require Carp;
  224.     my $class = ref($self);
  225.     Carp::croak ("Tried to set $self to NaN in $class\::_bnan()");
  226.     }
  227.  
  228.   $IMPORT=1;                    # call our import only once
  229.   $self->{_m} = $MBI->bzero();
  230.   $self->{_e} = $MBI->bzero();
  231.   }
  232.  
  233. sub _binf
  234.   {
  235.   # used by parent class bone() to initialize number to +-inf
  236.   my $self = shift;
  237.   
  238.   if ($_trap_inf)
  239.     {
  240.     require Carp;
  241.     my $class = ref($self);
  242.     Carp::croak ("Tried to set $self to +-inf in $class\::_binf()");
  243.     }
  244.  
  245.   $IMPORT=1;                    # call our import only once
  246.   $self->{_m} = $MBI->bzero();
  247.   $self->{_e} = $MBI->bzero();
  248.   }
  249.  
  250. sub _bone
  251.   {
  252.   # used by parent class bone() to initialize number to 1
  253.   my $self = shift;
  254.   $IMPORT=1;                    # call our import only once
  255.   $self->{_m} = $MBI->bone();
  256.   $self->{_e} = $MBI->bzero();
  257.   }
  258.  
  259. sub _bzero
  260.   {
  261.   # used by parent class bone() to initialize number to 0
  262.   my $self = shift;
  263.   $IMPORT=1;                    # call our import only once
  264.   $self->{_m} = $MBI->bzero();
  265.   $self->{_e} = $MBI->bone();
  266.   }
  267.  
  268. sub isa
  269.   {
  270.   my ($self,$class) = @_;
  271.   return if $class =~ /^Math::BigInt/;        # we aren't one of these
  272.   UNIVERSAL::isa($self,$class);
  273.   }
  274.  
  275. sub config
  276.   {
  277.   # return (later set?) configuration data as hash ref
  278.   my $class = shift || 'Math::BigFloat';
  279.  
  280.   my $cfg = $class->SUPER::config(@_);
  281.  
  282.   # now we need only to override the ones that are different from our parent
  283.   $cfg->{class} = $class;
  284.   $cfg->{with} = $MBI;
  285.   $cfg;
  286.   }
  287.  
  288. ##############################################################################
  289. # string conversation
  290.  
  291. sub bstr 
  292.   {
  293.   # (ref to BFLOAT or num_str ) return num_str
  294.   # Convert number from internal format to (non-scientific) string format.
  295.   # internal format is always normalized (no leading zeros, "-0" => "+0")
  296.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  297.  
  298.   if ($x->{sign} !~ /^[+-]$/)
  299.     {
  300.     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
  301.     return 'inf';                                       # +inf
  302.     }
  303.  
  304.   my $es = '0'; my $len = 1; my $cad = 0; my $dot = '.';
  305.  
  306.   # $x is zero?
  307.   my $not_zero = !($x->{sign} eq '+' && $x->{_m}->is_zero());
  308.   if ($not_zero)
  309.     {
  310.     $es = $x->{_m}->bstr();
  311.     $len = CORE::length($es);
  312.     my $e = $x->{_e}->numify();    
  313.     if ($e < 0)
  314.       {
  315.       $dot = '';
  316.       # if _e is bigger than a scalar, the following will blow your memory
  317.       if ($e <= -$len)
  318.         {
  319.         #print "style: 0.xxxx\n";
  320.         my $r = abs($e) - $len;
  321.         $es = '0.'. ('0' x $r) . $es; $cad = -($len+$r);
  322.         }
  323.       else
  324.         {
  325.         #print "insert '.' at $e in '$es'\n";
  326.         substr($es,$e,0) = '.'; $cad = $x->{_e};
  327.         }
  328.       }
  329.     elsif ($e > 0)
  330.       {
  331.       # expand with zeros
  332.       $es .= '0' x $e; $len += $e; $cad = 0;
  333.       }
  334.     } # if not zero
  335.   $es = '-'.$es if $x->{sign} eq '-';
  336.   # if set accuracy or precision, pad with zeros on the right side
  337.   if ((defined $x->{_a}) && ($not_zero))
  338.     {
  339.     # 123400 => 6, 0.1234 => 4, 0.001234 => 4
  340.     my $zeros = $x->{_a} - $cad;        # cad == 0 => 12340
  341.     $zeros = $x->{_a} - $len if $cad != $len;
  342.     $es .= $dot.'0' x $zeros if $zeros > 0;
  343.     }
  344.   elsif ((($x->{_p} || 0) < 0))
  345.     {
  346.     # 123400 => 6, 0.1234 => 4, 0.001234 => 6
  347.     my $zeros = -$x->{_p} + $cad;
  348.     $es .= $dot.'0' x $zeros if $zeros > 0;
  349.     }
  350.   $es;
  351.   }
  352.  
  353. sub bsstr
  354.   {
  355.   # (ref to BFLOAT or num_str ) return num_str
  356.   # Convert number from internal format to scientific string format.
  357.   # internal format is always normalized (no leading zeros, "-0E0" => "+0E0")
  358.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  359.  
  360.   if ($x->{sign} !~ /^[+-]$/)
  361.     {
  362.     return $x->{sign} unless $x->{sign} eq '+inf';      # -inf, NaN
  363.     return 'inf';                                       # +inf
  364.     }
  365.   # do $esign, because we need '1e+1', since $x->{_e}->bstr() misses the +
  366.   my $esign = $x->{_e}->{sign}; $esign = '' if $esign eq '-';
  367.   my $sep = 'e'.$esign;
  368.   my $sign = $x->{sign}; $sign = '' if $sign eq '+';
  369.   $sign . $x->{_m}->bstr() . $sep . $x->{_e}->bstr();
  370.   }
  371.     
  372. sub numify 
  373.   {
  374.   # Make a number from a BigFloat object
  375.   # simple return a string and let Perl's atoi()/atof() handle the rest
  376.   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
  377.   $x->bsstr(); 
  378.   }
  379.  
  380. ##############################################################################
  381. # public stuff (usually prefixed with "b")
  382.  
  383. # tels 2001-08-04 
  384. # XXX TODO this must be overwritten and return NaN for non-integer values
  385. # band(), bior(), bxor(), too
  386. #sub bnot
  387. #  {
  388. #  $class->SUPER::bnot($class,@_);
  389. #  }
  390.  
  391. sub bcmp 
  392.   {
  393.   # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
  394.  
  395.   # set up parameters
  396.   my ($self,$x,$y) = (ref($_[0]),@_);
  397.   # objectify is costly, so avoid it
  398.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  399.     {
  400.     ($self,$x,$y) = objectify(2,@_);
  401.     }
  402.  
  403.   return $upgrade->bcmp($x,$y) if defined $upgrade &&
  404.     ((!$x->isa($self)) || (!$y->isa($self)));
  405.  
  406.   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
  407.     {
  408.     # handle +-inf and NaN
  409.     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
  410.     return 0 if ($x->{sign} eq $y->{sign}) && ($x->{sign} =~ /^[+-]inf$/);
  411.     return +1 if $x->{sign} eq '+inf';
  412.     return -1 if $x->{sign} eq '-inf';
  413.     return -1 if $y->{sign} eq '+inf';
  414.     return +1;
  415.     }
  416.  
  417.   # check sign for speed first
  418.   return 1 if $x->{sign} eq '+' && $y->{sign} eq '-';    # does also 0 <=> -y
  419.   return -1 if $x->{sign} eq '-' && $y->{sign} eq '+';    # does also -x <=> 0
  420.  
  421.   # shortcut 
  422.   my $xz = $x->is_zero();
  423.   my $yz = $y->is_zero();
  424.   return 0 if $xz && $yz;                # 0 <=> 0
  425.   return -1 if $xz && $y->{sign} eq '+';        # 0 <=> +y
  426.   return 1 if $yz && $x->{sign} eq '+';            # +x <=> 0
  427.  
  428.   # adjust so that exponents are equal
  429.   my $lxm = $x->{_m}->length();
  430.   my $lym = $y->{_m}->length();
  431.   # the numify somewhat limits our length, but makes it much faster
  432.   my $lx = $lxm + $x->{_e}->numify();
  433.   my $ly = $lym + $y->{_e}->numify();
  434.   my $l = $lx - $ly; $l = -$l if $x->{sign} eq '-';
  435.   return $l <=> 0 if $l != 0;
  436.   
  437.   # lengths (corrected by exponent) are equal
  438.   # so make mantissa equal length by padding with zero (shift left)
  439.   my $diff = $lxm - $lym;
  440.   my $xm = $x->{_m};        # not yet copy it
  441.   my $ym = $y->{_m};
  442.   if ($diff > 0)
  443.     {
  444.     $ym = $y->{_m}->copy()->blsft($diff,10);
  445.     }
  446.   elsif ($diff < 0)
  447.     {
  448.     $xm = $x->{_m}->copy()->blsft(-$diff,10);
  449.     }
  450.   my $rc = $xm->bacmp($ym);
  451.   $rc = -$rc if $x->{sign} eq '-';        # -124 < -123
  452.   $rc <=> 0;
  453.   }
  454.  
  455. sub bacmp 
  456.   {
  457.   # Compares 2 values, ignoring their signs. 
  458.   # Returns one of undef, <0, =0, >0. (suitable for sort)
  459.   
  460.   # set up parameters
  461.   my ($self,$x,$y) = (ref($_[0]),@_);
  462.   # objectify is costly, so avoid it
  463.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  464.     {
  465.     ($self,$x,$y) = objectify(2,@_);
  466.     }
  467.  
  468.   return $upgrade->bacmp($x,$y) if defined $upgrade &&
  469.     ((!$x->isa($self)) || (!$y->isa($self)));
  470.  
  471.   # handle +-inf and NaN's
  472.   if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/)
  473.     {
  474.     return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
  475.     return 0 if ($x->is_inf() && $y->is_inf());
  476.     return 1 if ($x->is_inf() && !$y->is_inf());
  477.     return -1;
  478.     }
  479.  
  480.   # shortcut 
  481.   my $xz = $x->is_zero();
  482.   my $yz = $y->is_zero();
  483.   return 0 if $xz && $yz;                # 0 <=> 0
  484.   return -1 if $xz && !$yz;                # 0 <=> +y
  485.   return 1 if $yz && !$xz;                # +x <=> 0
  486.  
  487.   # adjust so that exponents are equal
  488.   my $lxm = $x->{_m}->length();
  489.   my $lym = $y->{_m}->length();
  490.   # the numify somewhat limits our length, but makes it much faster
  491.   my $lx = $lxm + $x->{_e}->numify();
  492.   my $ly = $lym + $y->{_e}->numify();
  493.   my $l = $lx - $ly;
  494.   return $l <=> 0 if $l != 0;
  495.   
  496.   # lengths (corrected by exponent) are equal
  497.   # so make mantissa equal-length by padding with zero (shift left)
  498.   my $diff = $lxm - $lym;
  499.   my $xm = $x->{_m};        # not yet copy it
  500.   my $ym = $y->{_m};
  501.   if ($diff > 0)
  502.     {
  503.     $ym = $y->{_m}->copy()->blsft($diff,10);
  504.     }
  505.   elsif ($diff < 0)
  506.     {
  507.     $xm = $x->{_m}->copy()->blsft(-$diff,10);
  508.     }
  509.   $xm->bacmp($ym) <=> 0;
  510.   }
  511.  
  512. sub badd 
  513.   {
  514.   # add second arg (BFLOAT or string) to first (BFLOAT) (modifies first)
  515.   # return result as BFLOAT
  516.  
  517.   # set up parameters
  518.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  519.   # objectify is costly, so avoid it
  520.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  521.     {
  522.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  523.     }
  524.  
  525.   # inf and NaN handling
  526.   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
  527.     {
  528.     # NaN first
  529.     return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
  530.     # inf handling
  531.     if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/))
  532.       {
  533.       # +inf++inf or -inf+-inf => same, rest is NaN
  534.       return $x if $x->{sign} eq $y->{sign};
  535.       return $x->bnan();
  536.       }
  537.     # +-inf + something => +inf; something +-inf => +-inf
  538.     $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/;
  539.     return $x;
  540.     }
  541.  
  542.   return $upgrade->badd($x,$y,$a,$p,$r) if defined $upgrade &&
  543.    ((!$x->isa($self)) || (!$y->isa($self)));
  544.  
  545.   # speed: no add for 0+y or x+0
  546.   return $x->bround($a,$p,$r) if $y->is_zero();        # x+0
  547.   if ($x->is_zero())                    # 0+y
  548.     {
  549.     # make copy, clobbering up x (modify in place!)
  550.     $x->{_e} = $y->{_e}->copy();
  551.     $x->{_m} = $y->{_m}->copy();
  552.     $x->{sign} = $y->{sign} || $nan;
  553.     return $x->round($a,$p,$r,$y);
  554.     }
  555.  
  556.   # take lower of the two e's and adapt m1 to it to match m2
  557.   my $e = $y->{_e};
  558.   $e = $MBI->bzero() if !defined $e;        # if no BFLOAT ?
  559.   $e = $e->copy();                # make copy (didn't do it yet)
  560.   $e->bsub($x->{_e});                # Ye - Xe
  561.   my $add = $y->{_m}->copy();
  562.   if ($e->{sign} eq '-')            # < 0
  563.     {
  564.     $x->{_e} += $e;                # need the sign of e
  565.     $x->{_m}->blsft($e->babs(),10);        # destroys copy of _e
  566.     }
  567.   elsif (!$e->is_zero())            # > 0
  568.     {
  569.     $add->blsft($e,10);
  570.     }
  571.   # else: both e are the same, so just leave them
  572.   $x->{_m}->{sign} = $x->{sign};         # fiddle with signs
  573.   $add->{sign} = $y->{sign};
  574.   $x->{_m} += $add;                 # finally do add/sub
  575.   $x->{sign} = $x->{_m}->{sign};         # re-adjust signs
  576.   $x->{_m}->{sign} = '+';            # mantissa always positiv
  577.   # delete trailing zeros, then round
  578.   $x->bnorm()->round($a,$p,$r,$y);
  579.   }
  580.  
  581. sub bsub 
  582.   {
  583.   # (BigFloat or num_str, BigFloat or num_str) return BigFloat
  584.   # subtract second arg from first, modify first
  585.  
  586.   # set up parameters
  587.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  588.   # objectify is costly, so avoid it
  589.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  590.     {
  591.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  592.     }
  593.  
  594.   if ($y->is_zero())        # still round for not adding zero
  595.     {
  596.     return $x->round($a,$p,$r);
  597.     }
  598.  
  599.   # $x - $y = -$x + $y 
  600.   $y->{sign} =~ tr/+-/-+/;    # does nothing for NaN
  601.   $x->badd($y,$a,$p,$r);    # badd does not leave internal zeros
  602.   $y->{sign} =~ tr/+-/-+/;    # refix $y (does nothing for NaN)
  603.   $x;                # already rounded by badd()
  604.   }
  605.  
  606. sub binc
  607.   {
  608.   # increment arg by one
  609.   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  610.  
  611.   if ($x->{_e}->sign() eq '-')
  612.     {
  613.     return $x->badd($self->bone(),@r);    #  digits after dot
  614.     }
  615.  
  616.   if (!$x->{_e}->is_zero())            # _e == 0 for NaN, inf, -inf
  617.     {
  618.     # 1e2 => 100, so after the shift below _m has a '0' as last digit
  619.     $x->{_m}->blsft($x->{_e},10);        # 1e2 => 100
  620.     $x->{_e}->bzero();                # normalize
  621.     # we know that the last digit of $x will be '1' or '9', depending on the
  622.     # sign
  623.     }
  624.   # now $x->{_e} == 0
  625.   if ($x->{sign} eq '+')
  626.     {
  627.     $x->{_m}->binc();
  628.     return $x->bnorm()->bround(@r);
  629.     }
  630.   elsif ($x->{sign} eq '-')
  631.     {
  632.     $x->{_m}->bdec();
  633.     $x->{sign} = '+' if $x->{_m}->is_zero(); # -1 +1 => -0 => +0
  634.     return $x->bnorm()->bround(@r);
  635.     }
  636.   # inf, nan handling etc
  637.   $x->badd($self->bone(),@r);            # badd() does round 
  638.   }
  639.  
  640. sub bdec
  641.   {
  642.   # decrement arg by one
  643.   my ($self,$x,@r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  644.  
  645.   if ($x->{_e}->sign() eq '-')
  646.     {
  647.     return $x->badd($self->bone('-'),@r);    #  digits after dot
  648.     }
  649.  
  650.   if (!$x->{_e}->is_zero())
  651.     {
  652.     $x->{_m}->blsft($x->{_e},10);        # 1e2 => 100
  653.     $x->{_e}->bzero();
  654.     }
  655.   # now $x->{_e} == 0
  656.   my $zero = $x->is_zero();
  657.   # <= 0
  658.   if (($x->{sign} eq '-') || $zero)
  659.     {
  660.     $x->{_m}->binc();
  661.     $x->{sign} = '-' if $zero;            # 0 => 1 => -1
  662.     $x->{sign} = '+' if $x->{_m}->is_zero();    # -1 +1 => -0 => +0
  663.     return $x->bnorm()->round(@r);
  664.     }
  665.   # > 0
  666.   elsif ($x->{sign} eq '+')
  667.     {
  668.     $x->{_m}->bdec();
  669.     return $x->bnorm()->round(@r);
  670.     }
  671.   # inf, nan handling etc
  672.   $x->badd($self->bone('-'),@r);        # does round 
  673.   } 
  674.  
  675. sub DEBUG () { 0; }
  676.  
  677. sub blog
  678.   {
  679.   my ($self,$x,$base,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  680.  
  681.   # $base > 0, $base != 1; if $base == undef default to $base == e
  682.   # $x >= 0
  683.  
  684.   # we need to limit the accuracy to protect against overflow
  685.   my $fallback = 0;
  686.   my ($scale,@params);
  687.   ($x,@params) = $x->_find_round_parameters($a,$p,$r);
  688.  
  689.   # also takes care of the "error in _find_round_parameters?" case
  690.   return $x->bnan() if $x->{sign} ne '+' || $x->is_zero();
  691.  
  692.   # no rounding at all, so must use fallback
  693.   if (scalar @params == 0)
  694.     {
  695.     # simulate old behaviour
  696.     $params[0] = $self->div_scale();    # and round to it as accuracy
  697.     $params[1] = undef;            # P = undef
  698.     $scale = $params[0]+4;         # at least four more for proper round
  699.     $params[2] = $r;            # round mode by caller or undef
  700.     $fallback = 1;            # to clear a/p afterwards
  701.     }
  702.   else
  703.     {
  704.     # the 4 below is empirical, and there might be cases where it is not
  705.     # enough...
  706.     $scale = abs($params[0] || $params[1]) + 4;    # take whatever is defined
  707.     }
  708.  
  709.   return $x->bzero(@params) if $x->is_one();
  710.   # base not defined => base == Euler's constant e
  711.   if (defined $base)
  712.     {
  713.     # make object, since we don't feed it through objectify() to still get the
  714.     # case of $base == undef
  715.     $base = $self->new($base) unless ref($base);
  716.     # $base > 0; $base != 1
  717.     return $x->bnan() if $base->is_zero() || $base->is_one() ||
  718.       $base->{sign} ne '+';
  719.     # if $x == $base, we know the result must be 1.0
  720.     return $x->bone('+',@params) if $x->bcmp($base) == 0;
  721.     }
  722.  
  723.   # when user set globals, they would interfere with our calculation, so
  724.   # disable them and later re-enable them
  725.   no strict 'refs';
  726.   my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
  727.   my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
  728.   # we also need to disable any set A or P on $x (_find_round_parameters took
  729.   # them already into account), since these would interfere, too
  730.   delete $x->{_a}; delete $x->{_p};
  731.   # need to disable $upgrade in BigInt, to avoid deep recursion
  732.   local $Math::BigInt::upgrade = undef;
  733.   local $Math::BigFloat::downgrade = undef;
  734.  
  735.   # upgrade $x if $x is not a BigFloat (handle BigInt input)
  736.   if (!$x->isa('Math::BigFloat'))
  737.     {
  738.     $x = Math::BigFloat->new($x);
  739.     $self = ref($x);
  740.     }
  741.   
  742.   my $done = 0;
  743.  
  744.   # If the base is defined and an integer, try to calculate integer result
  745.   # first. This is very fast, and in case the real result was found, we can
  746.   # stop right here.
  747.   if (defined $base && $base->is_int() && $x->is_int())
  748.     {
  749.     my $int = $x->{_m}->copy();
  750.     $int->blsft($x->{_e},10) unless $x->{_e}->is_zero();
  751.     $int->blog($base->as_number());
  752.     # if ($exact)
  753.     if ($base->copy()->bpow($int) == $x)
  754.       {
  755.       # found result, return it
  756.       $x->{_m} = $int;
  757.       $x->{_e} = $MBI->bzero();
  758.       $x->bnorm();
  759.       $done = 1;
  760.       }
  761.     }
  762.  
  763.   if ($done == 0)
  764.     {
  765.     # first calculate the log to base e (using reduction by 10 (and probably 2))
  766.     $self->_log_10($x,$scale);
  767.  
  768.     # and if a different base was requested, convert it
  769.     if (defined $base)
  770.       {
  771.       $base = Math::BigFloat->new($base) unless $base->isa('Math::BigFloat');
  772.       # not ln, but some other base (don't modify $base)
  773.       $x->bdiv( $base->copy()->blog(undef,$scale), $scale );
  774.       }
  775.     }
  776.  
  777.   # shortcut to not run through _find_round_parameters again
  778.   if (defined $params[0])
  779.     {
  780.     $x->bround($params[0],$params[2]);        # then round accordingly
  781.     }
  782.   else
  783.     {
  784.     $x->bfround($params[1],$params[2]);        # then round accordingly
  785.     }
  786.   if ($fallback)
  787.     {
  788.     # clear a/p after round, since user did not request it
  789.     delete $x->{_a}; delete $x->{_p};
  790.     }
  791.   # restore globals
  792.   $$abr = $ab; $$pbr = $pb;
  793.  
  794.   $x;
  795.   }
  796.  
  797. sub _log
  798.   {
  799.   # internal log function to calculate ln() based on Taylor series.
  800.   # Modifies $x in place.
  801.   my ($self,$x,$scale) = @_;
  802.  
  803.   # in case of $x == 1, result is 0
  804.   return $x->bzero() if $x->is_one();
  805.  
  806.   # http://www.efunda.com/math/taylor_series/logarithmic.cfm?search_string=log
  807.  
  808.   # u = x-1, v = x+1
  809.   #              _                               _
  810.   # Taylor:     |    u    1   u^3   1   u^5       |
  811.   # ln (x)  = 2 |   --- + - * --- + - * --- + ... |  x > 0
  812.   #             |_   v    3   v^3   5   v^5      _|
  813.  
  814.   # This takes much more steps to calculate the result and is thus not used
  815.   # u = x-1
  816.   #              _                               _
  817.   # Taylor:     |    u    1   u^2   1   u^3       |
  818.   # ln (x)  = 2 |   --- + - * --- + - * --- + ... |  x > 1/2
  819.   #             |_   x    2   x^2   3   x^3      _|
  820.  
  821.   my ($limit,$v,$u,$below,$factor,$two,$next,$over,$f);
  822.  
  823.   $v = $x->copy(); $v->binc();        # v = x+1
  824.   $x->bdec(); $u = $x->copy();        # u = x-1; x = x-1
  825.   $x->bdiv($v,$scale);            # first term: u/v
  826.   $below = $v->copy();
  827.   $over = $u->copy();
  828.   $u *= $u; $v *= $v;                # u^2, v^2
  829.   $below->bmul($v);                # u^3, v^3
  830.   $over->bmul($u);
  831.   $factor = $self->new(3); $f = $self->new(2);
  832.  
  833.   my $steps = 0 if DEBUG;  
  834.   $limit = $self->new("1E-". ($scale-1));
  835.   while (3 < 5)
  836.     {
  837.     # we calculate the next term, and add it to the last
  838.     # when the next term is below our limit, it won't affect the outcome
  839.     # anymore, so we stop
  840.  
  841.     # calculating the next term simple from over/below will result in quite
  842.     # a time hog if the input has many digits, since over and below will
  843.     # accumulate more and more digits, and the result will also have many
  844.     # digits, but in the end it is rounded to $scale digits anyway. So if we
  845.     # round $over and $below first, we save a lot of time for the division
  846.     # (not with log(1.2345), but try log (123**123) to see what I mean. This
  847.     # can introduce a rounding error if the division result would be f.i.
  848.     # 0.1234500000001 and we round it to 5 digits it would become 0.12346, but
  849.     # if we truncated $over and $below we might get 0.12345. Does this matter
  850.     # for the end result? So we give $over and $below 4 more digits to be
  851.     # on the safe side (unscientific error handling as usual... :+D
  852.     
  853.     $next = $over->copy->bround($scale+4)->bdiv(
  854.       $below->copy->bmul($factor)->bround($scale+4), 
  855.       $scale);
  856.  
  857. ## old version:    
  858. ##    $next = $over->copy()->bdiv($below->copy()->bmul($factor),$scale);
  859.  
  860.     last if $next->bacmp($limit) <= 0;
  861.  
  862.     delete $next->{_a}; delete $next->{_p};
  863.     $x->badd($next);
  864.     #print "step  $x\n  ($next - $limit = ",$next - $limit,")\n";
  865.     # calculate things for the next term
  866.     $over *= $u; $below *= $v; $factor->badd($f);
  867.     if (DEBUG)
  868.       {
  869.       $steps++; print "step $steps = $x\n" if $steps % 10 == 0;
  870.       }
  871.     }
  872.   $x->bmul($f);                    # $x *= 2
  873.   print "took $steps steps\n" if DEBUG;
  874.   }
  875.  
  876. sub _log_10
  877.   {
  878.   # Internal log function based on reducing input to the range of 0.1 .. 9.99
  879.   # and then "correcting" the result to the proper one. Modifies $x in place.
  880.   my ($self,$x,$scale) = @_;
  881.  
  882.   # taking blog() from numbers greater than 10 takes a *very long* time, so we
  883.   # break the computation down into parts based on the observation that:
  884.   #  blog(x*y) = blog(x) + blog(y)
  885.   # We set $y here to multiples of 10 so that $x is below 1 (the smaller $x is
  886.   # the faster it get's, especially because 2*$x takes about 10 times as long,
  887.   # so by dividing $x by 10 we make it at least factor 100 faster...)
  888.  
  889.   # The same observation is valid for numbers smaller than 0.1 (e.g. computing
  890.   # log(1) is fastest, and the farther away we get from 1, the longer it takes)
  891.   # so we also 'break' this down by multiplying $x with 10 and subtract the
  892.   # log(10) afterwards to get the correct result.
  893.  
  894.   # calculate nr of digits before dot
  895.   my $dbd = $x->{_m}->length() + $x->{_e}->numify();
  896.  
  897.   # more than one digit (e.g. at least 10), but *not* exactly 10 to avoid
  898.   # infinite recursion
  899.  
  900.   my $calc = 1;                    # do some calculation?
  901.  
  902.   # disable the shortcut for 10, since we need log(10) and this would recurse
  903.   # infinitely deep
  904.   if ($x->{_e}->is_one() && $x->{_m}->is_one())
  905.     {
  906.     $dbd = 0;                    # disable shortcut
  907.     # we can use the cached value in these cases
  908.     if ($scale <= $LOG_10_A)
  909.       {
  910.       $x->bzero(); $x->badd($LOG_10);
  911.       $calc = 0;                 # no need to calc, but round
  912.       }
  913.     }
  914.   else
  915.     {
  916.     # disable the shortcut for 2, since we maybe have it cached
  917.     if ($x->{_e}->is_zero() && $x->{_m}->bcmp(2) == 0)
  918.       {
  919.       $dbd = 0;                    # disable shortcut
  920.       # we can use the cached value in these cases
  921.       if ($scale <= $LOG_2_A)
  922.         {
  923.         $x->bzero(); $x->badd($LOG_2);
  924.         $calc = 0;                 # no need to calc, but round
  925.         }
  926.       }
  927.     }
  928.  
  929.   # if $x = 0.1, we know the result must be 0-log(10)
  930.   if ($calc != 0 && $x->{_e}->is_one('-') && $x->{_m}->is_one())
  931.     {
  932.     $dbd = 0;                    # disable shortcut
  933.     # we can use the cached value in these cases
  934.     if ($scale <= $LOG_10_A)
  935.       {
  936.       $x->bzero(); $x->bsub($LOG_10);
  937.       $calc = 0;                 # no need to calc, but round
  938.       }
  939.     }
  940.  
  941.   return if $calc == 0;                # already have the result
  942.  
  943.   # default: these correction factors are undef and thus not used
  944.   my $l_10;                # value of ln(10) to A of $scale
  945.   my $l_2;                # value of ln(2) to A of $scale
  946.  
  947.   # $x == 2 => 1, $x == 13 => 2, $x == 0.1 => 0, $x == 0.01 => -1
  948.   # so don't do this shortcut for 1 or 0
  949.   if (($dbd > 1) || ($dbd < 0))
  950.     {
  951.     # convert our cached value to an object if not already (avoid doing this
  952.     # at import() time, since not everybody needs this)
  953.     $LOG_10 = $self->new($LOG_10,undef,undef) unless ref $LOG_10;
  954.  
  955.     #print "x = $x, dbd = $dbd, calc = $calc\n";
  956.     # got more than one digit before the dot, or more than one zero after the
  957.     # dot, so do:
  958.     #  log(123)    == log(1.23) + log(10) * 2
  959.     #  log(0.0123) == log(1.23) - log(10) * 2
  960.   
  961.     if ($scale <= $LOG_10_A)
  962.       {
  963.       # use cached value
  964.       #print "using cached value for l_10\n";
  965.       $l_10 = $LOG_10->copy();        # copy for mul
  966.       }
  967.     else
  968.       {
  969.       # else: slower, compute it (but don't cache it, because it could be big)
  970.       # also disable downgrade for this code path
  971.       local $Math::BigFloat::downgrade = undef;
  972.       #print "l_10 = $l_10 (self = $self', 
  973.       #  ", ref(l_10) = ",ref($l_10)," scale $scale)\n";
  974.       #print "calculating value for l_10, scale $scale\n";
  975.       $l_10 = $self->new(10)->blog(undef,$scale);    # scale+4, actually
  976.       }
  977.     $dbd-- if ($dbd > 1);         # 20 => dbd=2, so make it dbd=1    
  978.     # make object
  979.     $dbd = $self->new($dbd);
  980.     #print "dbd $dbd\n";  
  981.     $l_10->bmul($dbd);            # log(10) * (digits_before_dot-1)
  982.     #print "l_10 = $l_10\n";
  983.     #print "x = $x";
  984.     $x->{_e}->bsub($dbd);        # 123 => 1.23
  985.     #print " => $x\n";
  986.     #print "calculating log($x) with scale=$scale\n";
  987.  
  988.     }
  989.  
  990.   # Now: 0.1 <= $x < 10 (and possible correction in l_10)
  991.  
  992.   ### Since $x in the range 0.5 .. 1.5 is MUCH faster, we do a repeated div
  993.   ### or mul by 2 (maximum times 3, since x < 10 and x > 0.1)
  994.  
  995.   my $half = $self->new('0.5');
  996.   my $twos = 0;                # default: none (0 times)    
  997.   my $two = $self->new(2);
  998.   while ($x->bacmp($half) <= 0)
  999.     {
  1000.     $twos--; $x->bmul($two);
  1001.     }
  1002.   while ($x->bacmp($two) >= 0)
  1003.     {
  1004.     $twos++; $x->bdiv($two,$scale+4);        # keep all digits
  1005.     }
  1006.   #print "$twos\n";
  1007.   # $twos > 0 => did mul 2, < 0 => did div 2 (never both)
  1008.   # calculate correction factor based on ln(2)
  1009.   if ($twos != 0)
  1010.     {
  1011.     $LOG_2 = $self->new($LOG_2,undef,undef) unless ref $LOG_2;
  1012.     if ($scale <= $LOG_2_A)
  1013.       {
  1014.       # use cached value
  1015.       #print "using cached value for l_10\n";
  1016.       $l_2 = $LOG_2->copy();            # copy for mul
  1017.       }
  1018.     else
  1019.       {
  1020.       # else: slower, compute it (but don't cache it, because it could be big)
  1021.       # also disable downgrade for this code path
  1022.       local $Math::BigFloat::downgrade = undef;
  1023.       #print "calculating value for l_2, scale $scale\n";
  1024.       $l_2 = $two->blog(undef,$scale);    # scale+4, actually
  1025.       }
  1026.     $l_2->bmul($twos);        # * -2 => subtract, * 2 => add
  1027.     }
  1028.   
  1029.   $self->_log($x,$scale);            # need to do the "normal" way
  1030.   $x->badd($l_10) if defined $l_10;         # correct it by ln(10)
  1031.   $x->badd($l_2) if defined $l_2;        # and maybe by ln(2)
  1032.   # all done, $x contains now the result
  1033.   }
  1034.  
  1035. sub blcm 
  1036.   { 
  1037.   # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
  1038.   # does not modify arguments, but returns new object
  1039.   # Lowest Common Multiplicator
  1040.  
  1041.   my ($self,@arg) = objectify(0,@_);
  1042.   my $x = $self->new(shift @arg);
  1043.   while (@arg) { $x = _lcm($x,shift @arg); } 
  1044.   $x;
  1045.   }
  1046.  
  1047. sub bgcd 
  1048.   { 
  1049.   # (BFLOAT or num_str, BFLOAT or num_str) return BINT
  1050.   # does not modify arguments, but returns new object
  1051.   # GCD -- Euclids algorithm Knuth Vol 2 pg 296
  1052.    
  1053.   my ($self,@arg) = objectify(0,@_);
  1054.   my $x = $self->new(shift @arg);
  1055.   while (@arg) { $x = _gcd($x,shift @arg); } 
  1056.   $x;
  1057.   }
  1058.  
  1059. ###############################################################################
  1060. # is_foo methods (is_negative, is_positive are inherited from BigInt)
  1061.  
  1062. sub _is_zero_or_one
  1063.   {
  1064.   # internal, return true if BigInt arg is zero or one, saving the
  1065.   # two calls to is_zero() and is_one() 
  1066.   my $x = $_[0];
  1067.  
  1068.   $x->{sign} eq '+' && ($x->is_zero() || $x->is_one());
  1069.   }
  1070.  
  1071. sub is_int
  1072.   {
  1073.   # return true if arg (BFLOAT or num_str) is an integer
  1074.   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
  1075.  
  1076.   return 1 if ($x->{sign} =~ /^[+-]$/) &&    # NaN and +-inf aren't
  1077.     $x->{_e}->{sign} eq '+';            # 1e-1 => no integer
  1078.   0;
  1079.   }
  1080.  
  1081. sub is_zero
  1082.   {
  1083.   # return true if arg (BFLOAT or num_str) is zero
  1084.   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
  1085.  
  1086.   return 1 if $x->{sign} eq '+' && $x->{_m}->is_zero();
  1087.   0;
  1088.   }
  1089.  
  1090. sub is_one
  1091.   {
  1092.   # return true if arg (BFLOAT or num_str) is +1 or -1 if signis given
  1093.   my ($self,$x,$sign) = ref($_[0]) ? (undef,@_) : objectify(1,@_);
  1094.  
  1095.   $sign = '+' if !defined $sign || $sign ne '-';
  1096.   return 1
  1097.    if ($x->{sign} eq $sign && $x->{_e}->is_zero() && $x->{_m}->is_one()); 
  1098.   0;
  1099.   }
  1100.  
  1101. sub is_odd
  1102.   {
  1103.   # return true if arg (BFLOAT or num_str) is odd or false if even
  1104.   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
  1105.   
  1106.   return 1 if ($x->{sign} =~ /^[+-]$/) &&        # NaN & +-inf aren't
  1107.     ($x->{_e}->is_zero() && $x->{_m}->is_odd()); 
  1108.   0;
  1109.   }
  1110.  
  1111. sub is_even
  1112.   {
  1113.   # return true if arg (BINT or num_str) is even or false if odd
  1114.   my ($self,$x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_);
  1115.  
  1116.   return 0 if $x->{sign} !~ /^[+-]$/;            # NaN & +-inf aren't
  1117.   return 1 if ($x->{_e}->{sign} eq '+'             # 123.45 is never
  1118.      && $x->{_m}->is_even());                 # but 1200 is
  1119.   0;
  1120.   }
  1121.  
  1122. sub bmul 
  1123.   { 
  1124.   # multiply two numbers -- stolen from Knuth Vol 2 pg 233
  1125.   # (BINT or num_str, BINT or num_str) return BINT
  1126.   
  1127.   # set up parameters
  1128.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  1129.   # objectify is costly, so avoid it
  1130.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1131.     {
  1132.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  1133.     }
  1134.  
  1135.   return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan));
  1136.  
  1137.   # inf handling
  1138.   if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/))
  1139.     {
  1140.     return $x->bnan() if $x->is_zero() || $y->is_zero(); 
  1141.     # result will always be +-inf:
  1142.     # +inf * +/+inf => +inf, -inf * -/-inf => +inf
  1143.     # +inf * -/-inf => -inf, -inf * +/+inf => -inf
  1144.     return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/);
  1145.     return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/);
  1146.     return $x->binf('-');
  1147.     }
  1148.   # handle result = 0
  1149.   return $x->bzero() if $x->is_zero() || $y->is_zero();
  1150.   
  1151.   return $upgrade->bmul($x,$y,$a,$p,$r) if defined $upgrade &&
  1152.    ((!$x->isa($self)) || (!$y->isa($self)));
  1153.  
  1154.   # aEb * cEd = (a*c)E(b+d)
  1155.   $x->{_m}->bmul($y->{_m});
  1156.   $x->{_e}->badd($y->{_e});
  1157.   # adjust sign:
  1158.   $x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+';
  1159.   return $x->bnorm()->round($a,$p,$r,$y);
  1160.   }
  1161.  
  1162. sub bdiv 
  1163.   {
  1164.   # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return 
  1165.   # (BFLOAT,BFLOAT) (quo,rem) or BFLOAT (only rem)
  1166.  
  1167.   # set up parameters
  1168.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  1169.   # objectify is costly, so avoid it
  1170.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1171.     {
  1172.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  1173.     }
  1174.  
  1175.   return $self->_div_inf($x,$y)
  1176.    if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/) || $y->is_zero());
  1177.  
  1178.   # x== 0 # also: or y == 1 or y == -1
  1179.   return wantarray ? ($x,$self->bzero()) : $x if $x->is_zero();
  1180.  
  1181.   # upgrade ?
  1182.   return $upgrade->bdiv($upgrade->new($x),$y,$a,$p,$r) if defined $upgrade;
  1183.  
  1184.   # we need to limit the accuracy to protect against overflow
  1185.   my $fallback = 0;
  1186.   my (@params,$scale);
  1187.   ($x,@params) = $x->_find_round_parameters($a,$p,$r,$y);
  1188.  
  1189.   return $x if $x->is_nan();        # error in _find_round_parameters?
  1190.  
  1191.   # no rounding at all, so must use fallback
  1192.   if (scalar @params == 0)
  1193.     {
  1194.     # simulate old behaviour
  1195.     $params[0] = $self->div_scale();    # and round to it as accuracy
  1196.     $scale = $params[0]+4;         # at least four more for proper round
  1197.     $params[2] = $r;            # round mode by caller or undef
  1198.     $fallback = 1;            # to clear a/p afterwards
  1199.     }
  1200.   else
  1201.     {
  1202.     # the 4 below is empirical, and there might be cases where it is not
  1203.     # enough...
  1204.     $scale = abs($params[0] || $params[1]) + 4;    # take whatever is defined
  1205.     }
  1206.   my $lx = $x->{_m}->length(); my $ly = $y->{_m}->length();
  1207.   $scale = $lx if $lx > $scale;
  1208.   $scale = $ly if $ly > $scale;
  1209.   my $diff = $ly - $lx;
  1210.   $scale += $diff if $diff > 0;        # if lx << ly, but not if ly << lx!
  1211.     
  1212.   # make copy of $x in case of list context for later reminder calculation
  1213.   my $rem;
  1214.   if (wantarray && !$y->is_one())
  1215.     {
  1216.     $rem = $x->copy();
  1217.     }
  1218.  
  1219.   $x->{sign} = $x->{sign} ne $y->sign() ? '-' : '+'; 
  1220.  
  1221.   # check for / +-1 ( +/- 1E0)
  1222.   if (!$y->is_one())
  1223.     {
  1224.     # promote BigInts and it's subclasses (except when already a BigFloat)
  1225.     $y = $self->new($y) unless $y->isa('Math::BigFloat'); 
  1226.  
  1227.     # need to disable $upgrade in BigInt, to avoid deep recursion
  1228.     local $Math::BigInt::upgrade = undef;     # should be parent class vs MBI
  1229.  
  1230.     # calculate the result to $scale digits and then round it
  1231.     # a * 10 ** b / c * 10 ** d => a/c * 10 ** (b-d)
  1232.     $x->{_m}->blsft($scale,10);
  1233.     $x->{_m}->bdiv( $y->{_m} );    # a/c
  1234.     $x->{_e}->bsub( $y->{_e} );    # b-d
  1235.     $x->{_e}->bsub($scale);    # correct for 10**scale
  1236.     $x->bnorm();        # remove trailing 0's
  1237.     }
  1238.  
  1239.   # shortcut to not run through _find_round_parameters again
  1240.   if (defined $params[0])
  1241.     {
  1242.     delete $x->{_a};                 # clear before round
  1243.     $x->bround($params[0],$params[2]);        # then round accordingly
  1244.     }
  1245.   else
  1246.     {
  1247.     delete $x->{_p};                 # clear before round
  1248.     $x->bfround($params[1],$params[2]);        # then round accordingly
  1249.     }
  1250.   if ($fallback)
  1251.     {
  1252.     # clear a/p after round, since user did not request it
  1253.     delete $x->{_a}; delete $x->{_p};
  1254.     }
  1255.   
  1256.   if (wantarray)
  1257.     {
  1258.     if (!$y->is_one())
  1259.       {
  1260.       $rem->bmod($y,@params);            # copy already done
  1261.       }
  1262.     else
  1263.       {
  1264.       $rem = $self->bzero();
  1265.       }
  1266.     if ($fallback)
  1267.       {
  1268.       # clear a/p after round, since user did not request it
  1269.       delete $rem->{_a}; delete $rem->{_p};
  1270.       }
  1271.     return ($x,$rem);
  1272.     }
  1273.   $x;
  1274.   }
  1275.  
  1276. sub bmod 
  1277.   {
  1278.   # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return reminder 
  1279.  
  1280.   # set up parameters
  1281.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  1282.   # objectify is costly, so avoid it
  1283.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1284.     {
  1285.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  1286.     }
  1287.  
  1288.   if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/))
  1289.     {
  1290.     my ($d,$re) = $self->SUPER::_div_inf($x,$y);
  1291.     $x->{sign} = $re->{sign};
  1292.     $x->{_e} = $re->{_e};
  1293.     $x->{_m} = $re->{_m};
  1294.     return $x->round($a,$p,$r,$y);
  1295.     } 
  1296.   return $x->bnan() if $x->is_zero() && $y->is_zero();
  1297.   return $x if $y->is_zero();
  1298.   return $x->bnan() if $x->is_nan() || $y->is_nan();
  1299.   return $x->bzero() if $y->is_one() || $x->is_zero();
  1300.  
  1301.   # inf handling is missing here
  1302.  
  1303.   my $cmp = $x->bacmp($y);            # equal or $x < $y?
  1304.   return $x->bzero($a,$p) if $cmp == 0;        # $x == $y => result 0
  1305.  
  1306.   # only $y of the operands negative? 
  1307.   my $neg = 0; $neg = 1 if $x->{sign} ne $y->{sign};
  1308.  
  1309.   $x->{sign} = $y->{sign};                # calc sign first
  1310.   return $x->round($a,$p,$r) if $cmp < 0 && $neg == 0;    # $x < $y => result $x
  1311.   
  1312.   my $ym = $y->{_m}->copy();
  1313.   
  1314.   # 2e1 => 20
  1315.   $ym->blsft($y->{_e},10) if $y->{_e}->{sign} eq '+' && !$y->{_e}->is_zero();
  1316.  
  1317.   # if $y has digits after dot
  1318.   my $shifty = 0;            # correct _e of $x by this
  1319.   if ($y->{_e}->{sign} eq '-')        # has digits after dot
  1320.     {
  1321.     # 123 % 2.5 => 1230 % 25 => 5 => 0.5
  1322.     $shifty = $y->{_e}->copy()->babs();    # no more digits after dot
  1323.     $x->blsft($shifty,10);        # 123 => 1230, $y->{_m} is already 25
  1324.     }
  1325.   # $ym is now mantissa of $y based on exponent 0
  1326.  
  1327.   my $shiftx = 0;            # correct _e of $x by this
  1328.   if ($x->{_e}->{sign} eq '-')        # has digits after dot
  1329.     {
  1330.     # 123.4 % 20 => 1234 % 200
  1331.     $shiftx = $x->{_e}->copy()->babs();    # no more digits after dot
  1332.     $ym->blsft($shiftx,10);
  1333.     }
  1334.   # 123e1 % 20 => 1230 % 20
  1335.   if ($x->{_e}->{sign} eq '+' && !$x->{_e}->is_zero())
  1336.     {
  1337.     $x->{_m}->blsft($x->{_e},10);
  1338.     }
  1339.   $x->{_e} = $MBI->bzero() unless $x->{_e}->is_zero();
  1340.   
  1341.   $x->{_e}->bsub($shiftx) if $shiftx != 0;
  1342.   $x->{_e}->bsub($shifty) if $shifty != 0;
  1343.   
  1344.   # now mantissas are equalized, exponent of $x is adjusted, so calc result
  1345.  
  1346.   $x->{_m}->bmod($ym);
  1347.  
  1348.   $x->{sign} = '+' if $x->{_m}->is_zero();        # fix sign for -0
  1349.   $x->bnorm();
  1350.  
  1351.   if ($neg != 0)    # one of them negative => correct in place
  1352.     {
  1353.     my $r = $y - $x;
  1354.     $x->{_m} = $r->{_m};
  1355.     $x->{_e} = $r->{_e};
  1356.     $x->{sign} = '+' if $x->{_m}->is_zero();        # fix sign for -0
  1357.     $x->bnorm();
  1358.     }
  1359.  
  1360.   $x->round($a,$p,$r,$y);    # round and return
  1361.   }
  1362.  
  1363. sub broot
  1364.   {
  1365.   # calculate $y'th root of $x
  1366.   
  1367.   # set up parameters
  1368.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  1369.   # objectify is costly, so avoid it
  1370.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1371.     {
  1372.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  1373.     }
  1374.  
  1375.   # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0
  1376.   return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() ||
  1377.          $y->{sign} !~ /^\+$/;
  1378.  
  1379.   return $x if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one();
  1380.   
  1381.   # we need to limit the accuracy to protect against overflow
  1382.   my $fallback = 0;
  1383.   my (@params,$scale);
  1384.   ($x,@params) = $x->_find_round_parameters($a,$p,$r);
  1385.  
  1386.   return $x if $x->is_nan();        # error in _find_round_parameters?
  1387.  
  1388.   # no rounding at all, so must use fallback
  1389.   if (scalar @params == 0) 
  1390.     {
  1391.     # simulate old behaviour
  1392.     $params[0] = $self->div_scale();    # and round to it as accuracy
  1393.     $scale = $params[0]+4;         # at least four more for proper round
  1394.     $params[2] = $r;            # round mode by caller or undef
  1395.     $fallback = 1;            # to clear a/p afterwards
  1396.     }
  1397.   else
  1398.     {
  1399.     # the 4 below is empirical, and there might be cases where it is not
  1400.     # enough...
  1401.     $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
  1402.     }
  1403.  
  1404.   # when user set globals, they would interfere with our calculation, so
  1405.   # disable them and later re-enable them
  1406.   no strict 'refs';
  1407.   my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
  1408.   my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
  1409.   # we also need to disable any set A or P on $x (_find_round_parameters took
  1410.   # them already into account), since these would interfere, too
  1411.   delete $x->{_a}; delete $x->{_p};
  1412.   # need to disable $upgrade in BigInt, to avoid deep recursion
  1413.   local $Math::BigInt::upgrade = undef;    # should be really parent class vs MBI
  1414.  
  1415.   # remember sign and make $x positive, since -4 ** (1/2) => -2
  1416.   my $sign = 0; $sign = 1 if $x->is_negative(); $x->babs();
  1417.  
  1418.   if ($y->bcmp(2) == 0)        # normal square root
  1419.     {
  1420.     $x->bsqrt($scale+4);
  1421.     }
  1422.   elsif ($y->is_one('-'))
  1423.     {
  1424.     # $x ** -1 => 1/$x
  1425.     my $u = $self->bone()->bdiv($x,$scale);
  1426.     # copy private parts over
  1427.     $x->{_m} = $u->{_m};
  1428.     $x->{_e} = $u->{_e};
  1429.     }
  1430.   else
  1431.     {
  1432.     # calculate the broot() as integer result first, and if it fits, return
  1433.     # it rightaway (but only if $x and $y are integer):
  1434.  
  1435.     my $done = 0;                # not yet
  1436.     if ($y->is_int() && $x->is_int())
  1437.       {
  1438.       my $int = $x->{_m}->copy();
  1439.       $int->blsft($x->{_e},10) unless $x->{_e}->is_zero();
  1440.       $int->broot($y->as_number());
  1441.       # if ($exact)
  1442.       if ($int->copy()->bpow($y) == $x)
  1443.         {
  1444.         # found result, return it
  1445.         $x->{_m} = $int;
  1446.         $x->{_e} = $MBI->bzero();
  1447.         $x->bnorm();
  1448.         $done = 1;
  1449.         }
  1450.       }
  1451.     if ($done == 0)
  1452.       {
  1453.       my $u = $self->bone()->bdiv($y,$scale+4);
  1454.       delete $u->{_a}; delete $u->{_p};         # otherwise it conflicts
  1455.       $x->bpow($u,$scale+4);                    # el cheapo
  1456.       }
  1457.     }
  1458.   $x->bneg() if $sign == 1;
  1459.   
  1460.   # shortcut to not run through _find_round_parameters again
  1461.   if (defined $params[0])
  1462.     {
  1463.     $x->bround($params[0],$params[2]);        # then round accordingly
  1464.     }
  1465.   else
  1466.     {
  1467.     $x->bfround($params[1],$params[2]);        # then round accordingly
  1468.     }
  1469.   if ($fallback)
  1470.     {
  1471.     # clear a/p after round, since user did not request it
  1472.     delete $x->{_a}; delete $x->{_p};
  1473.     }
  1474.   # restore globals
  1475.   $$abr = $ab; $$pbr = $pb;
  1476.   $x;
  1477.   }
  1478.  
  1479. sub bsqrt
  1480.   { 
  1481.   # calculate square root
  1482.   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  1483.  
  1484.   return $x->bnan() if $x->{sign} !~ /^[+]/;    # NaN, -inf or < 0
  1485.   return $x if $x->{sign} eq '+inf';        # sqrt(inf) == inf
  1486.   return $x->round($a,$p,$r) if $x->is_zero() || $x->is_one();
  1487.  
  1488.   # we need to limit the accuracy to protect against overflow
  1489.   my $fallback = 0;
  1490.   my (@params,$scale);
  1491.   ($x,@params) = $x->_find_round_parameters($a,$p,$r);
  1492.  
  1493.   return $x if $x->is_nan();        # error in _find_round_parameters?
  1494.  
  1495.   # no rounding at all, so must use fallback
  1496.   if (scalar @params == 0) 
  1497.     {
  1498.     # simulate old behaviour
  1499.     $params[0] = $self->div_scale();    # and round to it as accuracy
  1500.     $scale = $params[0]+4;         # at least four more for proper round
  1501.     $params[2] = $r;            # round mode by caller or undef
  1502.     $fallback = 1;            # to clear a/p afterwards
  1503.     }
  1504.   else
  1505.     {
  1506.     # the 4 below is empirical, and there might be cases where it is not
  1507.     # enough...
  1508.     $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
  1509.     }
  1510.  
  1511.   # when user set globals, they would interfere with our calculation, so
  1512.   # disable them and later re-enable them
  1513.   no strict 'refs';
  1514.   my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
  1515.   my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
  1516.   # we also need to disable any set A or P on $x (_find_round_parameters took
  1517.   # them already into account), since these would interfere, too
  1518.   delete $x->{_a}; delete $x->{_p};
  1519.   # need to disable $upgrade in BigInt, to avoid deep recursion
  1520.   local $Math::BigInt::upgrade = undef;    # should be really parent class vs MBI
  1521.  
  1522.   my $xas = $x->as_number();
  1523.   my $gs = $xas->copy()->bsqrt();    # some guess
  1524.  
  1525.   if (($x->{_e}->{sign} ne '-')        # guess can't be accurate if there are
  1526.                     # digits after the dot
  1527.    && ($xas->bacmp($gs * $gs) == 0))    # guess hit the nail on the head?
  1528.     {
  1529.     # exact result
  1530.     $x->{_m} = $gs; $x->{_e} = $MBI->bzero(); $x->bnorm();
  1531.     # shortcut to not run through _find_round_parameters again
  1532.     if (defined $params[0])
  1533.       {
  1534.       $x->bround($params[0],$params[2]);    # then round accordingly
  1535.       }
  1536.     else
  1537.       {
  1538.       $x->bfround($params[1],$params[2]);    # then round accordingly
  1539.       }
  1540.     if ($fallback)
  1541.       {
  1542.       # clear a/p after round, since user did not request it
  1543.       delete $x->{_a}; delete $x->{_p};
  1544.       }
  1545.     # re-enable A and P, upgrade is taken care of by "local"
  1546.     ${"$self\::accuracy"} = $ab; ${"$self\::precision"} = $pb;
  1547.     return $x;
  1548.     }
  1549.  
  1550.   # sqrt(2) = 1.4 because sqrt(2*100) = 1.4*10; so we can increase the accuracy
  1551.   # of the result by multipyling the input by 100 and then divide the integer
  1552.   # result of sqrt(input) by 10. Rounding afterwards returns the real result.
  1553.   # this will transform 123.456 (in $x) into 123456 (in $y1)
  1554.   my $y1 = $x->{_m}->copy();
  1555.   # We now make sure that $y1 has the same odd or even number of digits than
  1556.   # $x had. So when _e of $x is odd, we must shift $y1 by one digit left,
  1557.   # because we always must multiply by steps of 100 (sqrt(100) is 10) and not
  1558.   # steps of 10. The length of $x does not count, since an even or odd number
  1559.   # of digits before the dot is not changed by adding an even number of digits
  1560.   # after the dot (the result is still odd or even digits long).
  1561.   my $length = $y1->length();
  1562.   $y1->bmul(10) if $x->{_e}->is_odd();
  1563.   # now calculate how many digits the result of sqrt(y1) would have
  1564.   my $digits = int($length / 2);
  1565.   # but we need at least $scale digits, so calculate how many are missing
  1566.   my $shift = $scale - $digits;
  1567.   # that should never happen (we take care of integer guesses above)
  1568.   # $shift = 0 if $shift < 0; 
  1569.   # multiply in steps of 100, by shifting left two times the "missing" digits
  1570.   $y1->blsft($shift*2,10);
  1571.   # now take the square root and truncate to integer
  1572.   $y1->bsqrt();
  1573.   # By "shifting" $y1 right (by creating a negative _e) we calculate the final
  1574.   # result, which is than later rounded to the desired scale.
  1575.  
  1576.   # calculate how many zeros $x had after the '.' (or before it, depending
  1577.   #  on sign of $dat, the result should have half as many:
  1578.   my $dat = $length + $x->{_e}->numify();
  1579.  
  1580.   if ($dat > 0)
  1581.     {
  1582.     # no zeros after the dot (e.g. 1.23, 0.49 etc)
  1583.     # preserve half as many digits before the dot than the input had 
  1584.     # (but round this "up")
  1585.     $dat = int(($dat+1)/2);
  1586.     }
  1587.   else
  1588.     {
  1589.     $dat = int(($dat)/2);
  1590.     }
  1591.   $x->{_e}= $MBI->new( $dat - $y1->length() );
  1592.  
  1593.   $x->{_m} = $y1;
  1594.  
  1595.   # shortcut to not run through _find_round_parameters again
  1596.   if (defined $params[0])
  1597.     {
  1598.     $x->bround($params[0],$params[2]);        # then round accordingly
  1599.     }
  1600.   else
  1601.     {
  1602.     $x->bfround($params[1],$params[2]);        # then round accordingly
  1603.     }
  1604.   if ($fallback)
  1605.     {
  1606.     # clear a/p after round, since user did not request it
  1607.     delete $x->{_a}; delete $x->{_p};
  1608.     }
  1609.   # restore globals
  1610.   $$abr = $ab; $$pbr = $pb;
  1611.   $x;
  1612.   }
  1613.  
  1614. sub bfac
  1615.   {
  1616.   # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
  1617.   # compute factorial number, modifies first argument
  1618.  
  1619.   # set up parameters
  1620.   my ($self,$x,@r) = (ref($_[0]),@_);
  1621.   # objectify is costly, so avoid it
  1622.   ($self,$x,@r) = objectify(1,@_) if !ref($x);
  1623.  
  1624.  return $x if $x->{sign} eq '+inf';    # inf => inf
  1625.   return $x->bnan() 
  1626.     if (($x->{sign} ne '+') ||        # inf, NaN, <0 etc => NaN
  1627.      ($x->{_e}->{sign} ne '+'));    # digits after dot?
  1628.  
  1629.   # use BigInt's bfac() for faster calc
  1630.   if (! $x->{_e}->is_zero())
  1631.     {
  1632.     $x->{_m}->blsft($x->{_e},10);    # change 12e1 to 120e0
  1633.     $x->{_e}->bzero();
  1634.     }
  1635.   $x->{_m}->bfac();            # calculate factorial
  1636.   $x->bnorm()->round(@r);         # norm again and round result
  1637.   }
  1638.  
  1639. sub _pow
  1640.   {
  1641.   # Calculate a power where $y is a non-integer, like 2 ** 0.5
  1642.   my ($x,$y,$a,$p,$r) = @_;
  1643.   my $self = ref($x);
  1644.  
  1645.   # if $y == 0.5, it is sqrt($x)
  1646.   return $x->bsqrt($a,$p,$r,$y) if $y->bcmp('0.5') == 0;
  1647.  
  1648.   # Using:
  1649.   # a ** x == e ** (x * ln a)
  1650.  
  1651.   # u = y * ln x
  1652.   #                _                         _
  1653.   # Taylor:       |   u    u^2    u^3         |
  1654.   # x ** y  = 1 + |  --- + --- + ----- + ...  |
  1655.   #               |_  1    1*2   1*2*3       _|
  1656.  
  1657.   # we need to limit the accuracy to protect against overflow
  1658.   my $fallback = 0;
  1659.   my ($scale,@params);
  1660.   ($x,@params) = $x->_find_round_parameters($a,$p,$r);
  1661.     
  1662.   return $x if $x->is_nan();        # error in _find_round_parameters?
  1663.  
  1664.   # no rounding at all, so must use fallback
  1665.   if (scalar @params == 0)
  1666.     {
  1667.     # simulate old behaviour
  1668.     $params[0] = $self->div_scale();    # and round to it as accuracy
  1669.     $params[1] = undef;            # disable P
  1670.     $scale = $params[0]+4;         # at least four more for proper round
  1671.     $params[2] = $r;            # round mode by caller or undef
  1672.     $fallback = 1;            # to clear a/p afterwards
  1673.     }
  1674.   else
  1675.     {
  1676.     # the 4 below is empirical, and there might be cases where it is not
  1677.     # enough...
  1678.     $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
  1679.     }
  1680.  
  1681.   # when user set globals, they would interfere with our calculation, so
  1682.   # disable them and later re-enable them
  1683.   no strict 'refs';
  1684.   my $abr = "$self\::accuracy"; my $ab = $$abr; $$abr = undef;
  1685.   my $pbr = "$self\::precision"; my $pb = $$pbr; $$pbr = undef;
  1686.   # we also need to disable any set A or P on $x (_find_round_parameters took
  1687.   # them already into account), since these would interfere, too
  1688.   delete $x->{_a}; delete $x->{_p};
  1689.   # need to disable $upgrade in BigInt, to avoid deep recursion
  1690.   local $Math::BigInt::upgrade = undef;
  1691.  
  1692.   my ($limit,$v,$u,$below,$factor,$next,$over);
  1693.  
  1694.   $u = $x->copy()->blog(undef,$scale)->bmul($y);
  1695.   $v = $self->bone();                # 1
  1696.   $factor = $self->new(2);            # 2
  1697.   $x->bone();                    # first term: 1
  1698.  
  1699.   $below = $v->copy();
  1700.   $over = $u->copy();
  1701.  
  1702.   $limit = $self->new("1E-". ($scale-1));
  1703.   #my $steps = 0;
  1704.   while (3 < 5)
  1705.     {
  1706.     # we calculate the next term, and add it to the last
  1707.     # when the next term is below our limit, it won't affect the outcome
  1708.     # anymore, so we stop
  1709.     $next = $over->copy()->bdiv($below,$scale);
  1710.     last if $next->bacmp($limit) <= 0;
  1711.     $x->badd($next);
  1712.     # calculate things for the next term
  1713.     $over *= $u; $below *= $factor; $factor->binc();
  1714.     #$steps++;
  1715.     }
  1716.   
  1717.   # shortcut to not run through _find_round_parameters again
  1718.   if (defined $params[0])
  1719.     {
  1720.     $x->bround($params[0],$params[2]);        # then round accordingly
  1721.     }
  1722.   else
  1723.     {
  1724.     $x->bfround($params[1],$params[2]);        # then round accordingly
  1725.     }
  1726.   if ($fallback)
  1727.     {
  1728.     # clear a/p after round, since user did not request it
  1729.     delete $x->{_a}; delete $x->{_p};
  1730.     }
  1731.   # restore globals
  1732.   $$abr = $ab; $$pbr = $pb;
  1733.   $x;
  1734.   }
  1735.  
  1736. sub bpow 
  1737.   {
  1738.   # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT
  1739.   # compute power of two numbers, second arg is used as integer
  1740.   # modifies first argument
  1741.  
  1742.   # set up parameters
  1743.   my ($self,$x,$y,$a,$p,$r) = (ref($_[0]),@_);
  1744.   # objectify is costly, so avoid it
  1745.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1746.     {
  1747.     ($self,$x,$y,$a,$p,$r) = objectify(2,@_);
  1748.     }
  1749.  
  1750.   return $x if $x->{sign} =~ /^[+-]inf$/;
  1751.   return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan;
  1752.   return $x->bone() if $y->is_zero();
  1753.   return $x         if $x->is_one() || $y->is_one();
  1754.  
  1755.   return $x->_pow($y,$a,$p,$r) if !$y->is_int();    # non-integer power
  1756.  
  1757.   my $y1 = $y->as_number();        # make bigint
  1758.   # if ($x == -1)
  1759.   if ($x->{sign} eq '-' && $x->{_m}->is_one() && $x->{_e}->is_zero())
  1760.     {
  1761.     # if $x == -1 and odd/even y => +1/-1  because +-1 ^ (+-1) => +-1
  1762.     return $y1->is_odd() ? $x : $x->babs(1);
  1763.     }
  1764.   if ($x->is_zero())
  1765.     {
  1766.     return $x if $y->{sign} eq '+';     # 0**y => 0 (if not y <= 0)
  1767.     # 0 ** -y => 1 / (0 ** y) => / 0! (1 / 0 => +inf)
  1768.     $x->binf();
  1769.     }
  1770.  
  1771.   # calculate $x->{_m} ** $y and $x->{_e} * $y separately (faster)
  1772.   $y1->babs();
  1773.   $x->{_m}->bpow($y1);
  1774.   $x->{_e}->bmul($y1);
  1775.   $x->{sign} = $nan if $x->{_m}->{sign} eq $nan || $x->{_e}->{sign} eq $nan;
  1776.   $x->bnorm();
  1777.   if ($y->{sign} eq '-')
  1778.     {
  1779.     # modify $x in place!
  1780.     my $z = $x->copy(); $x->bzero()->binc();
  1781.     return $x->bdiv($z,$a,$p,$r);    # round in one go (might ignore y's A!)
  1782.     }
  1783.   $x->round($a,$p,$r,$y);
  1784.   }
  1785.  
  1786. ###############################################################################
  1787. # rounding functions
  1788.  
  1789. sub bfround
  1790.   {
  1791.   # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.'
  1792.   # $n == 0 means round to integer
  1793.   # expects and returns normalized numbers!
  1794.   my $x = shift; my $self = ref($x) || $x; $x = $self->new(shift) if !ref($x);
  1795.  
  1796.   return $x if $x->modify('bfround');
  1797.   
  1798.   my ($scale,$mode) = $x->_scale_p($self->precision(),$self->round_mode(),@_);
  1799.   return $x if !defined $scale;            # no-op
  1800.  
  1801.   # never round a 0, +-inf, NaN
  1802.   if ($x->is_zero())
  1803.     {
  1804.     $x->{_p} = $scale if !defined $x->{_p} || $x->{_p} < $scale; # -3 < -2
  1805.     return $x; 
  1806.     }
  1807.   return $x if $x->{sign} !~ /^[+-]$/;
  1808.  
  1809.   # don't round if x already has lower precision
  1810.   return $x if (defined $x->{_p} && $x->{_p} < 0 && $scale < $x->{_p});
  1811.  
  1812.   $x->{_p} = $scale;            # remember round in any case
  1813.   delete $x->{_a};            # and clear A
  1814.   if ($scale < 0)
  1815.     {
  1816.     # round right from the '.'
  1817.  
  1818.     return $x if $x->{_e}->{sign} eq '+';    # e >= 0 => nothing to round
  1819.  
  1820.     $scale = -$scale;                # positive for simplicity
  1821.     my $len = $x->{_m}->length();        # length of mantissa
  1822.  
  1823.     # the following poses a restriction on _e, but if _e is bigger than a
  1824.     # scalar, you got other problems (memory etc) anyway
  1825.     my $dad = -($x->{_e}->numify());        # digits after dot
  1826.     my $zad = 0;                # zeros after dot
  1827.     $zad = $dad - $len if (-$dad < -$len);    # for 0.00..00xxx style
  1828.     
  1829.     #print "scale $scale dad $dad zad $zad len $len\n";
  1830.     # number  bsstr   len zad dad    
  1831.     # 0.123   123e-3    3   0 3
  1832.     # 0.0123  123e-4    3   1 4
  1833.     # 0.001   1e-3      1   2 3
  1834.     # 1.23    123e-2    3   0 2
  1835.     # 1.2345  12345e-4    5   0 4
  1836.  
  1837.     # do not round after/right of the $dad
  1838.     return $x if $scale > $dad;            # 0.123, scale >= 3 => exit
  1839.  
  1840.     # round to zero if rounding inside the $zad, but not for last zero like:
  1841.     # 0.0065, scale -2, round last '0' with following '65' (scale == zad case)
  1842.     return $x->bzero() if $scale < $zad;
  1843.     if ($scale == $zad)            # for 0.006, scale -3 and trunc
  1844.       {
  1845.       $scale = -$len;
  1846.       }
  1847.     else
  1848.       {
  1849.       # adjust round-point to be inside mantissa
  1850.       if ($zad != 0)
  1851.         {
  1852.     $scale = $scale-$zad;
  1853.         }
  1854.       else
  1855.         {
  1856.         my $dbd = $len - $dad; $dbd = 0 if $dbd < 0;    # digits before dot
  1857.     $scale = $dbd+$scale;
  1858.         }
  1859.       }
  1860.     }
  1861.   else
  1862.     {
  1863.     # round left from the '.'
  1864.  
  1865.     # 123 => 100 means length(123) = 3 - $scale (2) => 1
  1866.  
  1867.     my $dbt = $x->{_m}->length(); 
  1868.     # digits before dot 
  1869.     my $dbd = $dbt + $x->{_e}->numify(); 
  1870.     # should be the same, so treat it as this 
  1871.     $scale = 1 if $scale == 0; 
  1872.     # shortcut if already integer 
  1873.     return $x if $scale == 1 && $dbt <= $dbd; 
  1874.     # maximum digits before dot 
  1875.     ++$dbd;
  1876.  
  1877.     if ($scale > $dbd) 
  1878.        { 
  1879.        # not enough digits before dot, so round to zero 
  1880.        return $x->bzero; 
  1881.        }
  1882.     elsif ( $scale == $dbd )
  1883.        { 
  1884.        # maximum 
  1885.        $scale = -$dbt; 
  1886.        } 
  1887.     else
  1888.        { 
  1889.        $scale = $dbd - $scale; 
  1890.        }
  1891.     }
  1892.   # pass sign to bround for rounding modes '+inf' and '-inf'
  1893.   $x->{_m}->{sign} = $x->{sign};
  1894.   $x->{_m}->bround($scale,$mode);
  1895.   $x->{_m}->{sign} = '+';        # fix sign back
  1896.   $x->bnorm();
  1897.   }
  1898.  
  1899. sub bround
  1900.   {
  1901.   # accuracy: preserve $N digits, and overwrite the rest with 0's
  1902.   my $x = shift; my $self = ref($x) || $x; $x = $self->new(shift) if !ref($x);
  1903.   
  1904.   if (($_[0] || 0) < 0)
  1905.     {
  1906.     require Carp; Carp::croak ('bround() needs positive accuracy');
  1907.     }
  1908.  
  1909.   my ($scale,$mode) = $x->_scale_a($self->accuracy(),$self->round_mode(),@_);
  1910.   return $x if !defined $scale;                # no-op
  1911.  
  1912.   return $x if $x->modify('bround');
  1913.  
  1914.   # scale is now either $x->{_a}, $accuracy, or the user parameter
  1915.   # test whether $x already has lower accuracy, do nothing in this case 
  1916.   # but do round if the accuracy is the same, since a math operation might
  1917.   # want to round a number with A=5 to 5 digits afterwards again
  1918.   return $x if defined $_[0] && defined $x->{_a} && $x->{_a} < $_[0];
  1919.  
  1920.   # scale < 0 makes no sense
  1921.   # never round a +-inf, NaN
  1922.   return $x if ($scale < 0) ||    $x->{sign} !~ /^[+-]$/;
  1923.  
  1924.   # 1: $scale == 0 => keep all digits
  1925.   # 2: never round a 0
  1926.   # 3: if we should keep more digits than the mantissa has, do nothing
  1927.   if ($scale == 0 || $x->is_zero() || $x->{_m}->length() <= $scale)
  1928.     {
  1929.     $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale;
  1930.     return $x; 
  1931.     }
  1932.  
  1933.   # pass sign to bround for '+inf' and '-inf' rounding modes
  1934.   $x->{_m}->{sign} = $x->{sign};
  1935.   $x->{_m}->bround($scale,$mode);    # round mantissa
  1936.   $x->{_m}->{sign} = '+';        # fix sign back
  1937.   $x->{_a} = $scale;            # remember rounding
  1938.   delete $x->{_p};            # and clear P
  1939.   $x->bnorm();                # del trailing zeros gen. by bround()
  1940.   }
  1941.  
  1942. sub bfloor
  1943.   {
  1944.   # return integer less or equal then $x
  1945.   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  1946.  
  1947.   return $x if $x->modify('bfloor');
  1948.    
  1949.   return $x if $x->{sign} !~ /^[+-]$/;    # nan, +inf, -inf
  1950.  
  1951.   # if $x has digits after dot
  1952.   if ($x->{_e}->{sign} eq '-')
  1953.     {
  1954.     $x->{_e}->{sign} = '+';            # negate e
  1955.     $x->{_m}->brsft($x->{_e},10);        # cut off digits after dot
  1956.     $x->{_e}->bzero();                # trunc/norm    
  1957.     $x->{_m}->binc() if $x->{sign} eq '-';    # decrement if negative
  1958.     }
  1959.   $x->round($a,$p,$r);
  1960.   }
  1961.  
  1962. sub bceil
  1963.   {
  1964.   # return integer greater or equal then $x
  1965.   my ($self,$x,$a,$p,$r) = ref($_[0]) ? (ref($_[0]),@_) : objectify(1,@_);
  1966.  
  1967.   return $x if $x->modify('bceil');
  1968.   return $x if $x->{sign} !~ /^[+-]$/;    # nan, +inf, -inf
  1969.  
  1970.   # if $x has digits after dot
  1971.   if ($x->{_e}->{sign} eq '-')
  1972.     {
  1973.     #$x->{_m}->brsft(-$x->{_e},10);
  1974.     #$x->{_e}->bzero();
  1975.     #$x++ if $x->{sign} eq '+';
  1976.  
  1977.     $x->{_e}->{sign} = '+';            # negate e
  1978.     $x->{_m}->brsft($x->{_e},10);        # cut off digits after dot
  1979.     $x->{_e}->bzero();                # trunc/norm    
  1980.     $x->{_m}->binc() if $x->{sign} eq '+';    # decrement if negative
  1981.     }
  1982.   $x->round($a,$p,$r);
  1983.   }
  1984.  
  1985. sub brsft
  1986.   {
  1987.   # shift right by $y (divide by power of $n)
  1988.   
  1989.   # set up parameters
  1990.   my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
  1991.   # objectify is costly, so avoid it
  1992.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  1993.     {
  1994.     ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
  1995.     }
  1996.  
  1997.   return $x if $x->modify('brsft');
  1998.   return $x if $x->{sign} !~ /^[+-]$/;    # nan, +inf, -inf
  1999.  
  2000.   $n = 2 if !defined $n; $n = $self->new($n);
  2001.   $x->bdiv($n->bpow($y),$a,$p,$r,$y);
  2002.   }
  2003.  
  2004. sub blsft
  2005.   {
  2006.   # shift left by $y (multiply by power of $n)
  2007.   
  2008.   # set up parameters
  2009.   my ($self,$x,$y,$n,$a,$p,$r) = (ref($_[0]),@_);
  2010.   # objectify is costly, so avoid it
  2011.   if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
  2012.     {
  2013.     ($self,$x,$y,$n,$a,$p,$r) = objectify(2,@_);
  2014.     }
  2015.  
  2016.   return $x if $x->modify('blsft');
  2017.   return $x if $x->{sign} !~ /^[+-]$/;    # nan, +inf, -inf
  2018.  
  2019.   $n = 2 if !defined $n; $n = $self->new($n);
  2020.   $x->bmul($n->bpow($y),$a,$p,$r,$y);
  2021.   }
  2022.  
  2023. ###############################################################################
  2024.  
  2025. sub DESTROY
  2026.   {
  2027.   # going through AUTOLOAD for every DESTROY is costly, avoid it by empty sub
  2028.   }
  2029.  
  2030. sub AUTOLOAD
  2031.   {
  2032.   # make fxxx and bxxx both work by selectively mapping fxxx() to MBF::bxxx()
  2033.   # or falling back to MBI::bxxx()
  2034.   my $name = $AUTOLOAD;
  2035.  
  2036.   $name =~ s/(.*):://;    # split package
  2037.   my $c = $1 || $class;
  2038.   no strict 'refs';
  2039.   $c->import() if $IMPORT == 0;
  2040.   if (!method_alias($name))
  2041.     {
  2042.     if (!defined $name)
  2043.       {
  2044.       # delayed load of Carp and avoid recursion    
  2045.       require Carp;
  2046.       Carp::croak ("$c: Can't call a method without name");
  2047.       }
  2048.     if (!method_hand_up($name))
  2049.       {
  2050.       # delayed load of Carp and avoid recursion    
  2051.       require Carp;
  2052.       Carp::croak ("Can't call $c\-\>$name, not a valid method");
  2053.       }
  2054.     # try one level up, but subst. bxxx() for fxxx() since MBI only got bxxx()
  2055.     $name =~ s/^f/b/;
  2056.     return &{"$MBI"."::$name"}(@_);
  2057.     }
  2058.   my $bname = $name; $bname =~ s/^f/b/;
  2059.   $c .= "::$name";
  2060.   *{$c} = \&{$bname};
  2061.   &{$c};    # uses @_
  2062.   }
  2063.  
  2064. sub exponent
  2065.   {
  2066.   # return a copy of the exponent
  2067.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2068.  
  2069.   if ($x->{sign} !~ /^[+-]$/)
  2070.     {
  2071.     my $s = $x->{sign}; $s =~ s/^[+-]//;
  2072.     return $self->new($s);             # -inf, +inf => +inf
  2073.     }
  2074.   return $x->{_e}->copy();
  2075.   }
  2076.  
  2077. sub mantissa
  2078.   {
  2079.   # return a copy of the mantissa
  2080.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2081.  
  2082.   if ($x->{sign} !~ /^[+-]$/)
  2083.     {
  2084.     my $s = $x->{sign}; $s =~ s/^[+]//;
  2085.     return $self->new($s);             # -inf, +inf => +inf
  2086.     }
  2087.   my $m = $x->{_m}->copy();        # faster than going via bstr()
  2088.   $m->bneg() if $x->{sign} eq '-';
  2089.  
  2090.   $m;
  2091.   }
  2092.  
  2093. sub parts
  2094.   {
  2095.   # return a copy of both the exponent and the mantissa
  2096.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2097.  
  2098.   if ($x->{sign} !~ /^[+-]$/)
  2099.     {
  2100.     my $s = $x->{sign}; $s =~ s/^[+]//; my $se = $s; $se =~ s/^[-]//;
  2101.     return ($self->new($s),$self->new($se)); # +inf => inf and -inf,+inf => inf
  2102.     }
  2103.   my $m = $x->{_m}->copy();    # faster than going via bstr()
  2104.   $m->bneg() if $x->{sign} eq '-';
  2105.   return ($m,$x->{_e}->copy());
  2106.   }
  2107.  
  2108. ##############################################################################
  2109. # private stuff (internal use only)
  2110.  
  2111. sub import
  2112.   {
  2113.   my $self = shift;
  2114.   my $l = scalar @_;
  2115.   my $lib = ''; my @a;
  2116.   $IMPORT=1;
  2117.   for ( my $i = 0; $i < $l ; $i++)
  2118.     {
  2119.     if ( $_[$i] eq ':constant' )
  2120.       {
  2121.       # This causes overlord er load to step in. 'binary' and 'integer'
  2122.       # are handled by BigInt.
  2123.       overload::constant float => sub { $self->new(shift); }; 
  2124.       }
  2125.     elsif ($_[$i] eq 'upgrade')
  2126.       {
  2127.       # this causes upgrading
  2128.       $upgrade = $_[$i+1];        # or undef to disable
  2129.       $i++;
  2130.       }
  2131.     elsif ($_[$i] eq 'downgrade')
  2132.       {
  2133.       # this causes downgrading
  2134.       $downgrade = $_[$i+1];        # or undef to disable
  2135.       $i++;
  2136.       }
  2137.     elsif ($_[$i] eq 'lib')
  2138.       {
  2139.       # alternative library
  2140.       $lib = $_[$i+1] || '';        # default Calc
  2141.       $i++;
  2142.       }
  2143.     elsif ($_[$i] eq 'with')
  2144.       {
  2145.       # alternative class for our private parts()
  2146.       $MBI = $_[$i+1] || 'Math::BigInt';    # default Math::BigInt
  2147.       $i++;
  2148.       }
  2149.     else
  2150.       {
  2151.       push @a, $_[$i];
  2152.       }
  2153.     }
  2154.  
  2155.   # let use Math::BigInt lib => 'GMP'; use Math::BigFloat; still work
  2156.   my $mbilib = eval { Math::BigInt->config()->{lib} };
  2157.   if ((defined $mbilib) && ($MBI eq 'Math::BigInt'))
  2158.     {
  2159.     # MBI already loaded
  2160.     $MBI->import('lib',"$lib,$mbilib", 'objectify');
  2161.     }
  2162.   else
  2163.     {
  2164.     # MBI not loaded, or with ne "Math::BigInt"
  2165.     $lib .= ",$mbilib" if defined $mbilib;
  2166.     $lib =~ s/^,//;                # don't leave empty 
  2167.     # replacement library can handle lib statement, but also could ignore it
  2168.     if ($] < 5.006)
  2169.       {
  2170.       # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
  2171.       # used in the same script, or eval inside import().
  2172.       my @parts = split /::/, $MBI;        # Math::BigInt => Math BigInt
  2173.       my $file = pop @parts; $file .= '.pm';    # BigInt => BigInt.pm
  2174.       require File::Spec;
  2175.       $file = File::Spec->catfile (@parts, $file);
  2176.       eval { require "$file"; };
  2177.       $MBI->import( lib => $lib, 'objectify' );
  2178.       }
  2179.     else
  2180.       {
  2181.       my $rc = "use $MBI lib => '$lib', 'objectify';";
  2182.       eval $rc;
  2183.       }
  2184.     }
  2185.   if ($@)
  2186.     {
  2187.     require Carp; Carp::croak ("Couldn't load $MBI: $! $@");
  2188.     }
  2189.  
  2190.   # any non :constant stuff is handled by our parent, Exporter
  2191.   # even if @_ is empty, to give it a chance
  2192.   $self->SUPER::import(@a);          # for subclasses
  2193.   $self->export_to_level(1,$self,@a);    # need this, too
  2194.   }
  2195.  
  2196. sub bnorm
  2197.   {
  2198.   # adjust m and e so that m is smallest possible
  2199.   # round number according to accuracy and precision settings
  2200.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2201.  
  2202.   return $x if $x->{sign} !~ /^[+-]$/;        # inf, nan etc
  2203.  
  2204.   my $zeros = $x->{_m}->_trailing_zeros();    # correct for trailing zeros 
  2205.   if ($zeros != 0)
  2206.     {
  2207.     my $z = $MBI->new($zeros,undef,undef);
  2208.     $x->{_m}->brsft($z,10); $x->{_e}->badd($z);
  2209.     }
  2210.   else
  2211.     {
  2212.     # $x can only be 0Ey if there are no trailing zeros ('0' has 0 trailing
  2213.     # zeros). So, for something like 0Ey, set y to 1, and -0 => +0
  2214.     $x->{sign} = '+', $x->{_e}->bone() if $x->{_m}->is_zero();
  2215.     }
  2216.  
  2217.   # this is to prevent automatically rounding when MBI's globals are set
  2218.   $x->{_m}->{_f} = MB_NEVER_ROUND;
  2219.   $x->{_e}->{_f} = MB_NEVER_ROUND;
  2220.   # 'forget' that mantissa was rounded via MBI::bround() in MBF's bfround()
  2221.   delete $x->{_m}->{_a}; delete $x->{_e}->{_a};
  2222.   delete $x->{_m}->{_p}; delete $x->{_e}->{_p};
  2223.   $x;                    # MBI bnorm is no-op, so dont call it
  2224.   } 
  2225.  
  2226. ##############################################################################
  2227.  
  2228. sub as_hex
  2229.   {
  2230.   # return number as hexadecimal string (only for integers defined)
  2231.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2232.  
  2233.   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
  2234.   return '0x0' if $x->is_zero();
  2235.  
  2236.   return $nan if $x->{_e}->{sign} ne '+';    # how to do 1e-1 in hex!?
  2237.  
  2238.   my $z = $x->{_m}->copy();
  2239.   if (!$x->{_e}->is_zero())        # > 0 
  2240.     {
  2241.     $z->blsft($x->{_e},10);
  2242.     }
  2243.   $z->{sign} = $x->{sign};
  2244.   $z->as_hex();
  2245.   }
  2246.  
  2247. sub as_bin
  2248.   {
  2249.   # return number as binary digit string (only for integers defined)
  2250.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2251.  
  2252.   return $x->bstr() if $x->{sign} !~ /^[+-]$/;  # inf, nan etc
  2253.   return '0b0' if $x->is_zero();
  2254.  
  2255.   return $nan if $x->{_e}->{sign} ne '+';    # how to do 1e-1 in hex!?
  2256.  
  2257.   my $z = $x->{_m}->copy();
  2258.   if (!$x->{_e}->is_zero())        # > 0 
  2259.     {
  2260.     $z->blsft($x->{_e},10);
  2261.     }
  2262.   $z->{sign} = $x->{sign};
  2263.   $z->as_bin();
  2264.   }
  2265.  
  2266. sub as_number
  2267.   {
  2268.   # return copy as a bigint representation of this BigFloat number
  2269.   my ($self,$x) = ref($_[0]) ? (ref($_[0]),$_[0]) : objectify(1,@_);
  2270.  
  2271.   my $z = $x->{_m}->copy();
  2272.   if ($x->{_e}->{sign} eq '-')        # < 0
  2273.     {
  2274.     $x->{_e}->{sign} = '+';        # flip
  2275.     $z->brsft($x->{_e},10);
  2276.     $x->{_e}->{sign} = '-';        # flip back
  2277.     } 
  2278.   elsif (!$x->{_e}->is_zero())        # > 0 
  2279.     {
  2280.     $z->blsft($x->{_e},10);
  2281.     }
  2282.   $z->{sign} = $x->{sign};
  2283.   $z;
  2284.   }
  2285.  
  2286. sub length
  2287.   {
  2288.   my $x = shift;
  2289.   my $class = ref($x) || $x;
  2290.   $x = $class->new(shift) unless ref($x);
  2291.  
  2292.   return 1 if $x->{_m}->is_zero();
  2293.   my $len = $x->{_m}->length();
  2294.   $len += $x->{_e} if $x->{_e}->sign() eq '+';
  2295.   if (wantarray())
  2296.     {
  2297.     my $t = $MBI->bzero();
  2298.     $t = $x->{_e}->copy()->babs() if $x->{_e}->sign() eq '-';
  2299.     return ($len,$t);
  2300.     }
  2301.   $len;
  2302.   }
  2303.  
  2304. 1;
  2305. __END__
  2306.  
  2307. =head1 NAME
  2308.  
  2309. Math::BigFloat - Arbitrary size floating point math package
  2310.  
  2311. =head1 SYNOPSIS
  2312.  
  2313.   use Math::BigFloat;
  2314.  
  2315.   # Number creation
  2316.   $x = Math::BigFloat->new($str);    # defaults to 0
  2317.   $nan  = Math::BigFloat->bnan();    # create a NotANumber
  2318.   $zero = Math::BigFloat->bzero();    # create a +0
  2319.   $inf = Math::BigFloat->binf();    # create a +inf
  2320.   $inf = Math::BigFloat->binf('-');    # create a -inf
  2321.   $one = Math::BigFloat->bone();    # create a +1
  2322.   $one = Math::BigFloat->bone('-');    # create a -1
  2323.  
  2324.   # Testing
  2325.   $x->is_zero();        # true if arg is +0
  2326.   $x->is_nan();            # true if arg is NaN
  2327.   $x->is_one();            # true if arg is +1
  2328.   $x->is_one('-');        # true if arg is -1
  2329.   $x->is_odd();            # true if odd, false for even
  2330.   $x->is_even();        # true if even, false for odd
  2331.   $x->is_pos();            # true if >= 0
  2332.   $x->is_neg();            # true if <  0
  2333.   $x->is_inf(sign);        # true if +inf, or -inf (default is '+')
  2334.  
  2335.   $x->bcmp($y);            # compare numbers (undef,<0,=0,>0)
  2336.   $x->bacmp($y);        # compare absolutely (undef,<0,=0,>0)
  2337.   $x->sign();            # return the sign, either +,- or NaN
  2338.   $x->digit($n);        # return the nth digit, counting from right
  2339.   $x->digit(-$n);        # return the nth digit, counting from left 
  2340.  
  2341.   # The following all modify their first argument. If you want to preserve
  2342.   # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is
  2343.   # neccessary when mixing $a = $b assigments with non-overloaded math.
  2344.  
  2345.   # set 
  2346.   $x->bzero();            # set $i to 0
  2347.   $x->bnan();            # set $i to NaN
  2348.   $x->bone();                   # set $x to +1
  2349.   $x->bone('-');                # set $x to -1
  2350.   $x->binf();                   # set $x to inf
  2351.   $x->binf('-');                # set $x to -inf
  2352.  
  2353.   $x->bneg();            # negation
  2354.   $x->babs();            # absolute value
  2355.   $x->bnorm();            # normalize (no-op)
  2356.   $x->bnot();            # two's complement (bit wise not)
  2357.   $x->binc();            # increment x by 1
  2358.   $x->bdec();            # decrement x by 1
  2359.   
  2360.   $x->badd($y);            # addition (add $y to $x)
  2361.   $x->bsub($y);            # subtraction (subtract $y from $x)
  2362.   $x->bmul($y);            # multiplication (multiply $x by $y)
  2363.   $x->bdiv($y);            # divide, set $x to quotient
  2364.                 # return (quo,rem) or quo if scalar
  2365.  
  2366.   $x->bmod($y);            # modulus ($x % $y)
  2367.   $x->bpow($y);            # power of arguments ($x ** $y)
  2368.   $x->blsft($y);        # left shift
  2369.   $x->brsft($y);        # right shift 
  2370.                 # return (quo,rem) or quo if scalar
  2371.   
  2372.   $x->blog();            # logarithm of $x to base e (Euler's number)
  2373.   $x->blog($base);        # logarithm of $x to base $base (f.i. 2)
  2374.   
  2375.   $x->band($y);            # bit-wise and
  2376.   $x->bior($y);            # bit-wise inclusive or
  2377.   $x->bxor($y);            # bit-wise exclusive or
  2378.   $x->bnot();            # bit-wise not (two's complement)
  2379.  
  2380.   $x->bsqrt();            # calculate square-root
  2381.   $x->broot($y);        # $y'th root of $x (e.g. $y == 3 => cubic root)
  2382.   $x->bfac();            # factorial of $x (1*2*3*4*..$x)
  2383.  
  2384.   $x->bround($N);         # accuracy: preserve $N digits
  2385.   $x->bfround($N);        # precision: round to the $Nth digit
  2386.  
  2387.   $x->bfloor();            # return integer less or equal than $x
  2388.   $x->bceil();            # return integer greater or equal than $x
  2389.  
  2390.   # The following do not modify their arguments:
  2391.  
  2392.   bgcd(@values);        # greatest common divisor
  2393.   blcm(@values);        # lowest common multiplicator
  2394.   
  2395.   $x->bstr();            # return string
  2396.   $x->bsstr();            # return string in scientific notation
  2397.  
  2398.   $x->as_int();            # return $x as BigInt 
  2399.   $x->exponent();        # return exponent as BigInt
  2400.   $x->mantissa();        # return mantissa as BigInt
  2401.   $x->parts();            # return (mantissa,exponent) as BigInt
  2402.  
  2403.   $x->length();            # number of digits (w/o sign and '.')
  2404.   ($l,$f) = $x->length();    # number of digits, and length of fraction    
  2405.  
  2406.   $x->precision();        # return P of $x (or global, if P of $x undef)
  2407.   $x->precision($n);        # set P of $x to $n
  2408.   $x->accuracy();        # return A of $x (or global, if A of $x undef)
  2409.   $x->accuracy($n);        # set A $x to $n
  2410.  
  2411.   # these get/set the appropriate global value for all BigFloat objects
  2412.   Math::BigFloat->precision();    # Precision
  2413.   Math::BigFloat->accuracy();    # Accuracy
  2414.   Math::BigFloat->round_mode();    # rounding mode
  2415.  
  2416. =head1 DESCRIPTION
  2417.  
  2418. All operators (inlcuding basic math operations) are overloaded if you
  2419. declare your big floating point numbers as
  2420.  
  2421.   $i = new Math::BigFloat '12_3.456_789_123_456_789E-2';
  2422.  
  2423. Operations with overloaded operators preserve the arguments, which is
  2424. exactly what you expect.
  2425.  
  2426. =head2 Canonical notation
  2427.  
  2428. Input to these routines are either BigFloat objects, or strings of the
  2429. following four forms:
  2430.  
  2431. =over 2
  2432.  
  2433. =item *
  2434.  
  2435. C</^[+-]\d+$/>
  2436.  
  2437. =item *
  2438.  
  2439. C</^[+-]\d+\.\d*$/>
  2440.  
  2441. =item *
  2442.  
  2443. C</^[+-]\d+E[+-]?\d+$/>
  2444.  
  2445. =item *
  2446.  
  2447. C</^[+-]\d*\.\d+E[+-]?\d+$/>
  2448.  
  2449. =back
  2450.  
  2451. all with optional leading and trailing zeros and/or spaces. Additonally,
  2452. numbers are allowed to have an underscore between any two digits.
  2453.  
  2454. Empty strings as well as other illegal numbers results in 'NaN'.
  2455.  
  2456. bnorm() on a BigFloat object is now effectively a no-op, since the numbers 
  2457. are always stored in normalized form. On a string, it creates a BigFloat 
  2458. object.
  2459.  
  2460. =head2 Output
  2461.  
  2462. Output values are BigFloat objects (normalized), except for bstr() and bsstr().
  2463.  
  2464. The string output will always have leading and trailing zeros stripped and drop
  2465. a plus sign. C<bstr()> will give you always the form with a decimal point,
  2466. while C<bsstr()> (s for scientific) gives you the scientific notation.
  2467.  
  2468.     Input            bstr()        bsstr()
  2469.     '-0'            '0'        '0E1'
  2470.        '  -123 123 123'    '-123123123'    '-123123123E0'
  2471.     '00.0123'        '0.0123'    '123E-4'
  2472.     '123.45E-2'        '1.2345'    '12345E-4'
  2473.     '10E+3'            '10000'        '1E4'
  2474.  
  2475. Some routines (C<is_odd()>, C<is_even()>, C<is_zero()>, C<is_one()>,
  2476. C<is_nan()>) return true or false, while others (C<bcmp()>, C<bacmp()>)
  2477. return either undef, <0, 0 or >0 and are suited for sort.
  2478.  
  2479. Actual math is done by using the class defined with C<with => Class;> (which
  2480. defaults to BigInts) to represent the mantissa and exponent.
  2481.  
  2482. The sign C</^[+-]$/> is stored separately. The string 'NaN' is used to 
  2483. represent the result when input arguments are not numbers, as well as 
  2484. the result of dividing by zero.
  2485.  
  2486. =head2 C<mantissa()>, C<exponent()> and C<parts()>
  2487.  
  2488. C<mantissa()> and C<exponent()> return the said parts of the BigFloat 
  2489. as BigInts such that:
  2490.  
  2491.     $m = $x->mantissa();
  2492.     $e = $x->exponent();
  2493.     $y = $m * ( 10 ** $e );
  2494.     print "ok\n" if $x == $y;
  2495.  
  2496. C<< ($m,$e) = $x->parts(); >> is just a shortcut giving you both of them.
  2497.  
  2498. A zero is represented and returned as C<0E1>, B<not> C<0E0> (after Knuth).
  2499.  
  2500. Currently the mantissa is reduced as much as possible, favouring higher
  2501. exponents over lower ones (e.g. returning 1e7 instead of 10e6 or 10000000e0).
  2502. This might change in the future, so do not depend on it.
  2503.  
  2504. =head2 Accuracy vs. Precision
  2505.  
  2506. See also: L<Rounding|Rounding>.
  2507.  
  2508. Math::BigFloat supports both precision and accuracy. For a full documentation,
  2509. examples and tips on these topics please see the large section in
  2510. L<Math::BigInt>.
  2511.  
  2512. Since things like sqrt(2) or 1/3 must presented with a limited precision lest
  2513. a operation consumes all resources, each operation produces no more than
  2514. the requested number of digits.
  2515.  
  2516. Please refer to BigInt's documentation for the precedence rules of which
  2517. accuracy/precision setting will be used.
  2518.  
  2519. If there is no gloabl precision set, B<and> the operation inquestion was not
  2520. called with a requested precision or accuracy, B<and> the input $x has no
  2521. accuracy or precision set, then a fallback parameter will be used. For
  2522. historical reasons, it is called C<div_scale> and can be accessed via:
  2523.  
  2524.     $d = Math::BigFloat->div_scale();        # query
  2525.     Math::BigFloat->div_scale($n);            # set to $n digits
  2526.  
  2527. The default value is 40 digits.
  2528.  
  2529. In case the result of one operation has more precision than specified,
  2530. it is rounded. The rounding mode taken is either the default mode, or the one
  2531. supplied to the operation after the I<scale>:
  2532.  
  2533.     $x = Math::BigFloat->new(2);
  2534.     Math::BigFloat->precision(5);        # 5 digits max
  2535.     $y = $x->copy()->bdiv(3);        # will give 0.66666
  2536.     $y = $x->copy()->bdiv(3,6);        # will give 0.666666
  2537.     $y = $x->copy()->bdiv(3,6,'odd');    # will give 0.666667
  2538.     Math::BigFloat->round_mode('zero');
  2539.     $y = $x->copy()->bdiv(3,6);        # will give 0.666666
  2540.  
  2541. =head2 Rounding
  2542.  
  2543. =over 2
  2544.  
  2545. =item ffround ( +$scale )
  2546.  
  2547. Rounds to the $scale'th place left from the '.', counting from the dot.
  2548. The first digit is numbered 1. 
  2549.  
  2550. =item ffround ( -$scale )
  2551.  
  2552. Rounds to the $scale'th place right from the '.', counting from the dot.
  2553.  
  2554. =item ffround ( 0 )
  2555.  
  2556. Rounds to an integer.
  2557.  
  2558. =item fround  ( +$scale )
  2559.  
  2560. Preserves accuracy to $scale digits from the left (aka significant digits)
  2561. and pads the rest with zeros. If the number is between 1 and -1, the
  2562. significant digits count from the first non-zero after the '.'
  2563.  
  2564. =item fround  ( -$scale ) and fround ( 0 )
  2565.  
  2566. These are effectively no-ops.
  2567.  
  2568. =back
  2569.  
  2570. All rounding functions take as a second parameter a rounding mode from one of
  2571. the following: 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'.
  2572.  
  2573. The default rounding mode is 'even'. By using
  2574. C<< Math::BigFloat->round_mode($round_mode); >> you can get and set the default
  2575. mode for subsequent rounding. The usage of C<$Math::BigFloat::$round_mode> is
  2576. no longer supported.
  2577. The second parameter to the round functions then overrides the default
  2578. temporarily. 
  2579.  
  2580. The C<as_number()> function returns a BigInt from a Math::BigFloat. It uses
  2581. 'trunc' as rounding mode to make it equivalent to:
  2582.  
  2583.     $x = 2.5;
  2584.     $y = int($x) + 2;
  2585.  
  2586. You can override this by passing the desired rounding mode as parameter to
  2587. C<as_number()>:
  2588.  
  2589.     $x = Math::BigFloat->new(2.5);
  2590.     $y = $x->as_number('odd');    # $y = 3
  2591.  
  2592. =head1 EXAMPLES
  2593.  
  2594.   # not ready yet
  2595.  
  2596. =head1 Autocreating constants
  2597.  
  2598. After C<use Math::BigFloat ':constant'> all the floating point constants
  2599. in the given scope are converted to C<Math::BigFloat>. This conversion
  2600. happens at compile time.
  2601.  
  2602. In particular
  2603.  
  2604.   perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"'
  2605.  
  2606. prints the value of C<2E-100>. Note that without conversion of 
  2607. constants the expression 2E-100 will be calculated as normal floating point 
  2608. number.
  2609.  
  2610. Please note that ':constant' does not affect integer constants, nor binary 
  2611. nor hexadecimal constants. Use L<bignum> or L<Math::BigInt> to get this to
  2612. work.
  2613.  
  2614. =head2 Math library
  2615.  
  2616. Math with the numbers is done (by default) by a module called
  2617. Math::BigInt::Calc. This is equivalent to saying:
  2618.  
  2619.     use Math::BigFloat lib => 'Calc';
  2620.  
  2621. You can change this by using:
  2622.  
  2623.     use Math::BigFloat lib => 'BitVect';
  2624.  
  2625. The following would first try to find Math::BigInt::Foo, then
  2626. Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:
  2627.  
  2628.     use Math::BigFloat lib => 'Foo,Math::BigInt::Bar';
  2629.  
  2630. Calc.pm uses as internal format an array of elements of some decimal base
  2631. (usually 1e7, but this might be differen for some systems) with the least
  2632. significant digit first, while BitVect.pm uses a bit vector of base 2, most
  2633. significant bit first. Other modules might use even different means of
  2634. representing the numbers. See the respective module documentation for further
  2635. details.
  2636.  
  2637. Please note that Math::BigFloat does B<not> use the denoted library itself,
  2638. but it merely passes the lib argument to Math::BigInt. So, instead of the need
  2639. to do:
  2640.  
  2641.     use Math::BigInt lib => 'GMP';
  2642.     use Math::BigFloat;
  2643.  
  2644. you can roll it all into one line:
  2645.  
  2646.     use Math::BigFloat lib => 'GMP';
  2647.  
  2648. It is also possible to just require Math::BigFloat:
  2649.  
  2650.     require Math::BigFloat;
  2651.  
  2652. This will load the neccessary things (like BigInt) when they are needed, and
  2653. automatically.
  2654.  
  2655. Use the lib, Luke! And see L<Using Math::BigInt::Lite> for more details than
  2656. you ever wanted to know about loading a different library.
  2657.  
  2658. =head2 Using Math::BigInt::Lite
  2659.  
  2660. It is possible to use L<Math::BigInt::Lite> with Math::BigFloat:
  2661.  
  2662.         # 1
  2663.         use Math::BigFloat with => 'Math::BigInt::Lite';
  2664.  
  2665. There is no need to "use Math::BigInt" or "use Math::BigInt::Lite", but you
  2666. can combine these if you want. For instance, you may want to use
  2667. Math::BigInt objects in your main script, too.
  2668.  
  2669.         # 2
  2670.         use Math::BigInt;
  2671.         use Math::BigFloat with => 'Math::BigInt::Lite';
  2672.  
  2673. Of course, you can combine this with the C<lib> parameter.
  2674.  
  2675.         # 3
  2676.         use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
  2677.  
  2678. There is no need for a "use Math::BigInt;" statement, even if you want to
  2679. use Math::BigInt's, since Math::BigFloat will needs Math::BigInt and thus
  2680. always loads it. But if you add it, add it B<before>:
  2681.  
  2682.         # 4
  2683.         use Math::BigInt;
  2684.         use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'GMP,Pari';
  2685.  
  2686. Notice that the module with the last C<lib> will "win" and thus
  2687. it's lib will be used if the lib is available:
  2688.  
  2689.         # 5
  2690.         use Math::BigInt lib => 'Bar,Baz';
  2691.         use Math::BigFloat with => 'Math::BigInt::Lite', lib => 'Foo';
  2692.  
  2693. That would try to load Foo, Bar, Baz and Calc (in that order). Or in other
  2694. words, Math::BigFloat will try to retain previously loaded libs when you
  2695. don't specify it onem but if you specify one, it will try to load them.
  2696.  
  2697. Actually, the lib loading order would be "Bar,Baz,Calc", and then
  2698. "Foo,Bar,Baz,Calc", but independend of which lib exists, the result is the
  2699. same as trying the latter load alone, except for the fact that one of Bar or
  2700. Baz might be loaded needlessly in an intermidiate step (and thus hang around
  2701. and waste memory). If neither Bar nor Baz exist (or don't work/compile), they
  2702. will still be tried to be loaded, but this is not as time/memory consuming as
  2703. actually loading one of them. Still, this type of usage is not recommended due
  2704. to these issues.
  2705.  
  2706. The old way (loading the lib only in BigInt) still works though:
  2707.  
  2708.         # 6
  2709.         use Math::BigInt lib => 'Bar,Baz';
  2710.         use Math::BigFloat;
  2711.  
  2712. You can even load Math::BigInt afterwards:
  2713.  
  2714.         # 7
  2715.         use Math::BigFloat;
  2716.         use Math::BigInt lib => 'Bar,Baz';
  2717.  
  2718. But this has the same problems like #5, it will first load Calc
  2719. (Math::BigFloat needs Math::BigInt and thus loads it) and then later Bar or
  2720. Baz, depending on which of them works and is usable/loadable. Since this
  2721. loads Calc unnecc., it is not recommended.
  2722.  
  2723. Since it also possible to just require Math::BigFloat, this poses the question
  2724. about what libary this will use:
  2725.  
  2726.     require Math::BigFloat;
  2727.     my $x = Math::BigFloat->new(123); $x += 123;
  2728.  
  2729. It will use Calc. Please note that the call to import() is still done, but
  2730. only when you use for the first time some Math::BigFloat math (it is triggered
  2731. via any constructor, so the first time you create a Math::BigFloat, the load
  2732. will happen in the background). This means:
  2733.  
  2734.     require Math::BigFloat;
  2735.     Math::BigFloat->import ( lib => 'Foo,Bar' );
  2736.  
  2737. would be the same as:
  2738.  
  2739.     use Math::BigFloat lib => 'Foo, Bar';
  2740.  
  2741. But don't try to be clever to insert some operations in between:
  2742.  
  2743.     require Math::BigFloat;
  2744.     my $x = Math::BigFloat->bone() + 4;        # load BigInt and Calc
  2745.     Math::BigFloat->import( lib => 'Pari' );    # load Pari, too
  2746.     $x = Math::BigFloat->bone()+4;            # now use Pari
  2747.  
  2748. While this works, it loads Calc needlessly. But maybe you just wanted that?
  2749.  
  2750. B<Examples #3 is highly recommended> for daily usage.
  2751.  
  2752. =head1 BUGS
  2753.  
  2754. Please see the file BUGS in the CPAN distribution Math::BigInt for known bugs.
  2755.  
  2756. =head1 CAVEATS
  2757.  
  2758. =over 1
  2759.  
  2760. =item stringify, bstr()
  2761.  
  2762. Both stringify and bstr() now drop the leading '+'. The old code would return
  2763. '+1.23', the new returns '1.23'. See the documentation in L<Math::BigInt> for
  2764. reasoning and details.
  2765.  
  2766. =item bdiv
  2767.  
  2768. The following will probably not do what you expect:
  2769.  
  2770.     print $c->bdiv(123.456),"\n";
  2771.  
  2772. It prints both quotient and reminder since print works in list context. Also,
  2773. bdiv() will modify $c, so be carefull. You probably want to use
  2774.     
  2775.     print $c / 123.456,"\n";
  2776.     print scalar $c->bdiv(123.456),"\n";  # or if you want to modify $c
  2777.  
  2778. instead.
  2779.  
  2780. =item Modifying and =
  2781.  
  2782. Beware of:
  2783.  
  2784.     $x = Math::BigFloat->new(5);
  2785.     $y = $x;
  2786.  
  2787. It will not do what you think, e.g. making a copy of $x. Instead it just makes
  2788. a second reference to the B<same> object and stores it in $y. Thus anything
  2789. that modifies $x will modify $y (except overloaded math operators), and vice
  2790. versa. See L<Math::BigInt> for details and how to avoid that.
  2791.  
  2792. =item bpow
  2793.  
  2794. C<bpow()> now modifies the first argument, unlike the old code which left
  2795. it alone and only returned the result. This is to be consistent with
  2796. C<badd()> etc. The first will modify $x, the second one won't:
  2797.  
  2798.     print bpow($x,$i),"\n";     # modify $x
  2799.     print $x->bpow($i),"\n";     # ditto
  2800.     print $x ** $i,"\n";        # leave $x alone 
  2801.  
  2802. =back
  2803.  
  2804. =head1 SEE ALSO
  2805.  
  2806. L<Math::BigInt>, L<Math::BigRat> and L<Math::Big> as well as
  2807. L<Math::BigInt::BitVect>, L<Math::BigInt::Pari> and  L<Math::BigInt::GMP>.
  2808.  
  2809. The pragmas L<bignum>, L<bigint> and L<bigrat> might also be of interest
  2810. because they solve the autoupgrading/downgrading issue, at least partly.
  2811.  
  2812. The package at
  2813. L<http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt> contains
  2814. more documentation including a full version history, testcases, empty
  2815. subclass files and benchmarks.
  2816.  
  2817. =head1 LICENSE
  2818.  
  2819. This program is free software; you may redistribute it and/or modify it under
  2820. the same terms as Perl itself.
  2821.  
  2822. =head1 AUTHORS
  2823.  
  2824. Mark Biggar, overloaded interface by Ilya Zakharevich.
  2825. Completely rewritten by Tels http://bloodgate.com in 2001, 2002, and still
  2826. at it in 2003.
  2827.  
  2828. =cut
  2829.