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