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