home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / lib / Math / BigFloat.pm next >
Encoding:
Perl POD Document  |  2002-07-13  |  69.9 KB  |  2,355 lines

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