<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#
# "Tax the rat farms." - Lord Vetinari
#

# The following hash values are used:

#          sign : "+", "-", "+inf", "-inf", or "NaN"
#            _d : denominator
#            _n : numerator (value = _n/_d)
#      accuracy : accuracy
#     precision : precision

# You should not look at the innards of a BigRat - use the methods for this.

package Math::BigRat;

use 5.006;
use strict;
use warnings;

use Carp            qw&lt; carp croak &gt;;
use Scalar::Util    qw&lt; blessed &gt;;

use Math::BigFloat ();

our $VERSION = '2.003002';
$VERSION =~ tr/_//d;

our @ISA = qw(Math::BigFloat);

our ($accuracy, $precision, $round_mode, $div_scale,
     $upgrade, $downgrade, $_trap_nan, $_trap_inf);

use overload

  # overload key: with_assign

  '+'     =&gt;      sub { $_[0] -&gt; copy() -&gt; badd($_[1]); },

  '-'     =&gt;      sub { my $c = $_[0] -&gt; copy;
                        $_[2] ? $c -&gt; bneg() -&gt; badd( $_[1])
                              : $c -&gt; bsub($_[1]); },

  '*'     =&gt;      sub { $_[0] -&gt; copy() -&gt; bmul($_[1]); },

  '/'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bdiv($_[0])
                              : $_[0] -&gt; copy() -&gt; bdiv($_[1]); },

  '%'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bmod($_[0])
                              : $_[0] -&gt; copy() -&gt; bmod($_[1]); },

  '**'    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bpow($_[0])
                              : $_[0] -&gt; copy() -&gt; bpow($_[1]); },

  '&lt;&lt;'    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bblsft($_[0])
                              : $_[0] -&gt; copy() -&gt; bblsft($_[1]); },

  '&gt;&gt;'    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bbrsft($_[0])
                              : $_[0] -&gt; copy() -&gt; bbrsft($_[1]); },

  # overload key: assign

  '+='    =&gt;      sub { $_[0] -&gt; badd($_[1]); },

  '-='    =&gt;      sub { $_[0] -&gt; bsub($_[1]); },

  '*='    =&gt;      sub { $_[0] -&gt; bmul($_[1]); },

  '/='    =&gt;      sub { scalar $_[0] -&gt; bdiv($_[1]); },

  '%='    =&gt;      sub { $_[0] -&gt; bmod($_[1]); },

  '**='   =&gt;      sub { $_[0] -&gt; bpow($_[1]); },

  '&lt;&lt;='   =&gt;      sub { $_[0] -&gt; bblsft($_[1]); },

  '&gt;&gt;='   =&gt;      sub { $_[0] -&gt; bbrsft($_[1]); },

#  'x='    =&gt;      sub { },

#  '.='    =&gt;      sub { },

  # overload key: num_comparison

  '&lt;'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; blt($_[0])
                              : $_[0] -&gt; blt($_[1]); },

  '&lt;='    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; ble($_[0])
                              : $_[0] -&gt; ble($_[1]); },

  '&gt;'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bgt($_[0])
                              : $_[0] -&gt; bgt($_[1]); },

  '&gt;='    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bge($_[0])
                              : $_[0] -&gt; bge($_[1]); },

  '=='    =&gt;      sub { $_[0] -&gt; beq($_[1]); },

  '!='    =&gt;      sub { $_[0] -&gt; bne($_[1]); },

  # overload key: 3way_comparison

  '&lt;=&gt;'   =&gt;      sub { my $cmp = $_[0] -&gt; bcmp($_[1]);
                        defined($cmp) &amp;&amp; $_[2] ? -$cmp : $cmp; },

  'cmp'   =&gt;      sub { $_[2] ? "$_[1]" cmp $_[0] -&gt; bstr()
                              : $_[0] -&gt; bstr() cmp "$_[1]"; },

  # overload key: str_comparison

#  'lt'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bstrlt($_[0])
#                              : $_[0] -&gt; bstrlt($_[1]); },
#
#  'le'    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bstrle($_[0])
#                              : $_[0] -&gt; bstrle($_[1]); },
#
#  'gt'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bstrgt($_[0])
#                              : $_[0] -&gt; bstrgt($_[1]); },
#
#  'ge'    =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bstrge($_[0])
#                              : $_[0] -&gt; bstrge($_[1]); },
#
#  'eq'    =&gt;      sub { $_[0] -&gt; bstreq($_[1]); },
#
#  'ne'    =&gt;      sub { $_[0] -&gt; bstrne($_[1]); },

  # overload key: binary

  '&amp;'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; band($_[0])
                              : $_[0] -&gt; copy() -&gt; band($_[1]); },

  '&amp;='    =&gt;      sub { $_[0] -&gt; band($_[1]); },

  '|'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bior($_[0])
                              : $_[0] -&gt; copy() -&gt; bior($_[1]); },

  '|='    =&gt;      sub { $_[0] -&gt; bior($_[1]); },

  '^'     =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; bxor($_[0])
                              : $_[0] -&gt; copy() -&gt; bxor($_[1]); },

  '^='    =&gt;      sub { $_[0] -&gt; bxor($_[1]); },

#  '&amp;.'    =&gt;      sub { },

#  '&amp;.='   =&gt;      sub { },

#  '|.'    =&gt;      sub { },

#  '|.='   =&gt;      sub { },

#  '^.'    =&gt;      sub { },

#  '^.='   =&gt;      sub { },

  # overload key: unary

  'neg'   =&gt;      sub { $_[0] -&gt; copy() -&gt; bneg(); },

#  '!'     =&gt;      sub { },

  '~'     =&gt;      sub { $_[0] -&gt; copy() -&gt; bnot(); },

#  '~.'    =&gt;      sub { },

  # overload key: mutators

  '++'    =&gt;      sub { $_[0] -&gt; binc() },

  '--'    =&gt;      sub { $_[0] -&gt; bdec() },

  # overload key: func

  'atan2' =&gt;      sub { $_[2] ? ref($_[0]) -&gt; new($_[1]) -&gt; batan2($_[0])
                              : $_[0] -&gt; copy() -&gt; batan2($_[1]); },

  'cos'   =&gt;      sub { $_[0] -&gt; copy() -&gt; bcos(); },

  'sin'   =&gt;      sub { $_[0] -&gt; copy() -&gt; bsin(); },

  'exp'   =&gt;      sub { $_[0] -&gt; copy() -&gt; bexp($_[1]); },

  'abs'   =&gt;      sub { $_[0] -&gt; copy() -&gt; babs(); },

  'log'   =&gt;      sub { $_[0] -&gt; copy() -&gt; blog(); },

  'sqrt'  =&gt;      sub { $_[0] -&gt; copy() -&gt; bsqrt(); },

  'int'   =&gt;      sub { $_[0] -&gt; copy() -&gt; bint(); },

  # overload key: conversion

  'bool'  =&gt;      sub { $_[0] -&gt; is_zero() ? '' : 1; },

  '""'    =&gt;      sub { $_[0] -&gt; bstr(); },

  '0+'    =&gt;      sub { $_[0] -&gt; numify(); },

  '='     =&gt;      sub { $_[0]-&gt;copy(); },

  ;

BEGIN {
    *objectify = \&amp;Math::BigInt::objectify;

    *AUTOLOAD  = \&amp;Math::BigFloat::AUTOLOAD; # can't inherit AUTOLOAD
    *as_number = \&amp;as_int;
    *is_pos = \&amp;is_positive;
    *is_neg = \&amp;is_negative;
}

##############################################################################
# Global constants and flags. Access these only via the accessor methods!

$accuracy   = $precision = undef;
$round_mode = 'even';
$div_scale  = 40;
$upgrade    = undef;
$downgrade  = undef;

# These are internally, and not to be used from the outside at all!

$_trap_nan = 0;                         # are NaNs ok? set w/ config()
$_trap_inf = 0;                         # are infs ok? set w/ config()

# the math backend library

my $LIB = 'Math::BigInt::Calc';

my $nan   = 'NaN';

# Has import() been called yet? This variable is needed to make "require" work.

my $IMPORT = 0;

# Compare the following function with @ISA above. This inheritance mess needs a
# clean up. When doing so, also consider the BEGIN block and the AUTOLOAD code.
# Fixme!

sub isa {
    return 0 if $_[1] =~ /^Math::Big(Int|Float)/;       # we aren't
    UNIVERSAL::isa(@_);
}

##############################################################################

sub new {
    my $proto    = shift;
    my $protoref = ref $proto;
    my $class    = $protoref || $proto;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    # Check the way we are called.

    if ($protoref) {
        croak("new() is a class method, not an instance method");
    }

    if (@_ &lt; 1) {
        #carp("Using new() with no argument is deprecated;",
        #           " use bzero() or new(0) instead");
        return $class -&gt; bzero();
    }

    if (@_ &gt; 2) {
        carp("Superfluous arguments to new() ignored.");
    }

    # Get numerator and denominator. If any of the arguments is undefined,
    # return zero.

    my ($n, $d) = @_;

    if (@_ == 1 &amp;&amp; !defined $n ||
        @_ == 2 &amp;&amp; (!defined $n || !defined $d))
    {
        #carp("Use of uninitialized value in new()");
        return $class -&gt; bzero();
    }

    # Initialize a new object.

    my $self = bless {}, $class;

    # One or two input arguments may be given. First handle the numerator $n.

    if (ref($n)) {
        $n = Math::BigFloat -&gt; new($n, undef, undef)
          unless ($n -&gt; isa('Math::BigRat') ||
                  $n -&gt; isa('Math::BigInt') ||
                  $n -&gt; isa('Math::BigFloat'));
    } else {
        if (defined $d) {
            # If the denominator is defined, the numerator is not a string
            # fraction, e.g., "355/113".
            $n = Math::BigFloat -&gt; new($n, undef, undef);
        } else {
            # If the denominator is undefined, the numerator might be a string
            # fraction, e.g., "355/113".
            if ($n =~ m| ^ \s* (\S+) \s* / \s* (\S+) \s* $ |x) {
                $n = Math::BigFloat -&gt; new($1, undef, undef);
                $d = Math::BigFloat -&gt; new($2, undef, undef);
            } else {
                $n = Math::BigFloat -&gt; new($n, undef, undef);
            }
        }
    }

    # At this point $n is an object and $d is either an object or undefined. An
    # undefined $d means that $d was not specified by the caller (not that $d
    # was specified as an undefined value).

    unless (defined $d) {
        #return $n -&gt; copy($n)               if $n -&gt; isa('Math::BigRat');
        if ($n -&gt; isa('Math::BigRat')) {
            return $downgrade -&gt; new($n)
              if defined($downgrade) &amp;&amp; $n -&gt; is_int();
            return $class -&gt; copy($n);
        }

        if ($n -&gt; is_nan()) {
            return $class -&gt; bnan();
        }

        if ($n -&gt; is_inf()) {
            return $class -&gt; binf($n -&gt; sign());
        }

        if ($n -&gt; isa('Math::BigInt')) {
            $self -&gt; {_n}   = $LIB -&gt; _new($n -&gt; copy() -&gt; babs(undef, undef)
                                              -&gt; bstr());
            $self -&gt; {_d}   = $LIB -&gt; _one();
            $self -&gt; {sign} = $n -&gt; sign();
            return $downgrade -&gt; new($n) if defined $downgrade;
            return $self;
        }

        if ($n -&gt; isa('Math::BigFloat')) {
            my $m = $n -&gt; mantissa(undef, undef) -&gt; babs(undef, undef);
            my $e = $n -&gt; exponent(undef, undef);
            $self -&gt; {_n} = $LIB -&gt; _new($m -&gt; bstr());
            $self -&gt; {_d} = $LIB -&gt; _one();

            if ($e &gt; 0) {
                $self -&gt; {_n} = $LIB -&gt; _lsft($self -&gt; {_n},
                                              $LIB -&gt; _new($e -&gt; bstr()), 10);
            } elsif ($e &lt; 0) {
                $self -&gt; {_d} = $LIB -&gt; _lsft($self -&gt; {_d},
                                              $LIB -&gt; _new(-$e -&gt; bstr()), 10);

                my $gcd = $LIB -&gt; _gcd($LIB -&gt; _copy($self -&gt; {_n}),
                                       $self -&gt; {_d});
                if (!$LIB -&gt; _is_one($gcd)) {
                    $self -&gt; {_n} = $LIB -&gt; _div($self-&gt;{_n}, $gcd);
                    $self -&gt; {_d} = $LIB -&gt; _div($self-&gt;{_d}, $gcd);
                }
            }

            $self -&gt; {sign} = $n -&gt; sign();
            return $downgrade -&gt; new($n, undef, undef)
              if defined($downgrade) &amp;&amp; $n -&gt; is_int();
            return $self;
        }

        die "I don't know how to handle this";  # should never get here
    }

    # At the point we know that both $n and $d are defined. We know that $n is
    # an object, but $d might still be a scalar. Now handle $d.

    $d = Math::BigFloat -&gt; new($d, undef, undef)
      unless ref($d) &amp;&amp; ($d -&gt; isa('Math::BigRat') ||
                         $d -&gt; isa('Math::BigInt') ||
                         $d -&gt; isa('Math::BigFloat'));

    # At this point both $n and $d are objects.

    if ($n -&gt; is_nan() || $d -&gt; is_nan()) {
        return $class -&gt; bnan();
    }

    # At this point neither $n nor $d is a NaN.

    if ($n -&gt; is_zero()) {
        if ($d -&gt; is_zero()) {     # 0/0 = NaN
            return $class -&gt; bnan();
        }
        return $class -&gt; bzero();
    }

    if ($d -&gt; is_zero()) {
        return $class -&gt; binf($d -&gt; sign());
    }

    # At this point, neither $n nor $d is a NaN or a zero.

    # Copy them now before manipulating them.

    $n = $n -&gt; copy();
    $d = $d -&gt; copy();

    if ($d &lt; 0) {               # make sure denominator is positive
        $n -&gt; bneg();
        $d -&gt; bneg();
    }

    if ($n -&gt; is_inf()) {
        return $class -&gt; bnan() if $d -&gt; is_inf();      # Inf/Inf = NaN
        return $class -&gt; binf($n -&gt; sign());
    }

    # At this point $n is finite.

    return $class -&gt; bzero()            if $d -&gt; is_inf();
    return $class -&gt; binf($d -&gt; sign()) if $d -&gt; is_zero();

    # At this point both $n and $d are finite and non-zero.

    if ($n &lt; 0) {
        $n -&gt; bneg();
        $self -&gt; {sign} = '-';
    } else {
        $self -&gt; {sign} = '+';
    }

    if ($n -&gt; isa('Math::BigRat')) {

        if ($d -&gt; isa('Math::BigRat')) {

            # At this point both $n and $d is a Math::BigRat.

            # p   r    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
            # - / -  = ----- =  ---------------------------------
            # q   s    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

            my $p = $n -&gt; {_n};
            my $q = $n -&gt; {_d};
            my $r = $d -&gt; {_n};
            my $s = $d -&gt; {_d};
            my $gcd_pr = $LIB -&gt; _gcd($LIB -&gt; _copy($p), $r);
            my $gcd_sq = $LIB -&gt; _gcd($LIB -&gt; _copy($s), $q);
            $self -&gt; {_n} = $LIB -&gt; _mul($LIB -&gt; _div($LIB -&gt; _copy($p), $gcd_pr),
                                         $LIB -&gt; _div($LIB -&gt; _copy($s), $gcd_sq));
            $self -&gt; {_d} = $LIB -&gt; _mul($LIB -&gt; _div($LIB -&gt; _copy($q), $gcd_sq),
                                         $LIB -&gt; _div($LIB -&gt; _copy($r), $gcd_pr));

            return $downgrade -&gt; new($n-&gt;bstr())
              if defined($downgrade) &amp;&amp; $self -&gt; is_int();
            return $self;       # no need for $self -&gt; bnorm() here
        }

        # At this point, $n is a Math::BigRat and $d is a Math::Big(Int|Float).

        my $p = $n -&gt; {_n};
        my $q = $n -&gt; {_d};
        my $m = $d -&gt; mantissa();
        my $e = $d -&gt; exponent();

        #                   /      p
        #                  |  ------------  if e &gt; 0
        #                  |  q * m * 10^e
        #                  |
        # p                |    p
        # - / (m * 10^e) = |  -----         if e == 0
        # q                |  q * m
        #                  |
        #                  |  p * 10^-e
        #                  |  --------      if e &lt; 0
        #                   \  q * m

        $self -&gt; {_n} = $LIB -&gt; _copy($p);
        $self -&gt; {_d} = $LIB -&gt; _mul($LIB -&gt; _copy($q), $m);
        if ($e &gt; 0) {
            $self -&gt; {_d} = $LIB -&gt; _lsft($self -&gt; {_d}, $e, 10);
        } elsif ($e &lt; 0) {
            $self -&gt; {_n} = $LIB -&gt; _lsft($self -&gt; {_n}, -$e, 10);
        }

        return $self -&gt; bnorm();

    } else {

        if ($d -&gt; isa('Math::BigRat')) {

            # At this point $n is a Math::Big(Int|Float) and $d is a
            # Math::BigRat.

            my $m = $n -&gt; mantissa();
            my $e = $n -&gt; exponent();
            my $p = $d -&gt; {_n};
            my $q = $d -&gt; {_d};

            #                   /  q * m * 10^e
            #                  |   ------------  if e &gt; 0
            #                  |        p
            #                  |
            #              p   |   m * q
            # (m * 10^e) / - = |   -----         if e == 0
            #              q   |     p
            #                  |
            #                  |     q * m
            #                  |   ---------     if e &lt; 0
            #                   \  p * 10^-e

            $self -&gt; {_n} = $LIB -&gt; _mul($LIB -&gt; _copy($q), $m);
            $self -&gt; {_d} = $LIB -&gt; _copy($p);
            if ($e &gt; 0) {
                $self -&gt; {_n} = $LIB -&gt; _lsft($self -&gt; {_n}, $e, 10);
            } elsif ($e &lt; 0) {
                $self -&gt; {_d} = $LIB -&gt; _lsft($self -&gt; {_d}, -$e, 10);
            }
            return $self -&gt; bnorm();

        } else {

            # At this point $n and $d are both a Math::Big(Int|Float)

            my $m1 = $n -&gt; mantissa();
            my $e1 = $n -&gt; exponent();
            my $m2 = $d -&gt; mantissa();
            my $e2 = $d -&gt; exponent();

            #               /
            #              |  m1 * 10^(e1 - e2)
            #              |  -----------------  if e1 &gt; e2
            #              |         m2
            #              |
            # m1 * 10^e1   |  m1
            # ---------- = |  --                 if e1 = e2
            # m2 * 10^e2   |  m2
            #              |
            #              |         m1
            #              |  -----------------  if e1 &lt; e2
            #              |  m2 * 10^(e2 - e1)
            #               \

            $self -&gt; {_n} = $LIB -&gt; _new($m1 -&gt; bstr());
            $self -&gt; {_d} = $LIB -&gt; _new($m2 -&gt; bstr());
            my $ediff = $e1 - $e2;
            if ($ediff &gt; 0) {
                $self -&gt; {_n} = $LIB -&gt; _lsft($self -&gt; {_n},
                                              $LIB -&gt; _new($ediff -&gt; bstr()),
                                              10);
            } elsif ($ediff &lt; 0) {
                $self -&gt; {_d} = $LIB -&gt; _lsft($self -&gt; {_d},
                                              $LIB -&gt; _new(-$ediff -&gt; bstr()),
                                              10);
            }

            return $self -&gt; bnorm();
        }
    }

    return $downgrade -&gt; new($self -&gt; bstr())
      if defined($downgrade) &amp;&amp; $self -&gt; is_int();
    return $self;
}

sub copy {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # If called as a class method, the object to copy is the next argument.

    $self = shift() unless $selfref;

    my $copy = bless {}, $class;

    $copy-&gt;{sign} = $self-&gt;{sign};
    $copy-&gt;{_d} = $LIB-&gt;_copy($self-&gt;{_d});
    $copy-&gt;{_n} = $LIB-&gt;_copy($self-&gt;{_n});
    $copy-&gt;{accuracy} = $self-&gt;{accuracy} if defined $self-&gt;{accuracy};
    $copy-&gt;{precision} = $self-&gt;{precision} if defined $self-&gt;{precision};

    #($copy, $copy-&gt;{accuracy}, $copy-&gt;{precision})
    #  = $copy-&gt;_find_round_parameters(@_);

    return $copy;
}

sub bnan {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    $self = bless {}, $class unless $selfref;

    if ($_trap_nan) {
        croak ("Tried to set a variable to NaN in $class-&gt;bnan()");
    }

    return $downgrade -&gt; bnan() if defined $downgrade;

    $self -&gt; {sign} = $nan;
    $self -&gt; {_n}   = $LIB -&gt; _zero();
    $self -&gt; {_d}   = $LIB -&gt; _one();

    ($self, $self-&gt;{accuracy}, $self-&gt;{precision})
      = $self-&gt;_find_round_parameters(@_);

    return $self;
}

sub binf {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    $self = bless {}, $class unless $selfref;

    my $sign = shift();
    $sign = defined($sign) &amp;&amp; substr($sign, 0, 1) eq '-' ? '-inf' : '+inf';

    if ($_trap_inf) {
        croak ("Tried to set a variable to +-inf in $class-&gt;binf()");
    }

    return $downgrade -&gt; binf($sign) if defined $downgrade;

    $self -&gt; {sign} = $sign;
    $self -&gt; {_n}   = $LIB -&gt; _zero();
    $self -&gt; {_d}   = $LIB -&gt; _one();

    ($self, $self-&gt;{accuracy}, $self-&gt;{precision})
      = $self-&gt;_find_round_parameters(@_);

    return $self;
}

sub bone {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    my $sign = shift();
    $sign = '+' unless defined($sign) &amp;&amp; $sign eq '-';

    return $downgrade -&gt; bone($sign) if defined $downgrade;

    $self = bless {}, $class unless $selfref;
    $self -&gt; {sign} = $sign;
    $self -&gt; {_n}   = $LIB -&gt; _one();
    $self -&gt; {_d}   = $LIB -&gt; _one();

    ($self, $self-&gt;{accuracy}, $self-&gt;{precision})
      = $self-&gt;_find_round_parameters(@_);

    return $self;
}

sub bzero {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    return $downgrade -&gt; bzero() if defined $downgrade;

    $self = bless {}, $class unless $selfref;
    $self -&gt; {sign} = '+';
    $self -&gt; {_n}   = $LIB -&gt; _zero();
    $self -&gt; {_d}   = $LIB -&gt; _one();

    ($self, $self-&gt;{accuracy}, $self-&gt;{precision})
      = $self-&gt;_find_round_parameters(@_);

    return $self;
}

##############################################################################

sub config {
    # return (later set?) configuration data as hash ref
    my $class = shift() || 'Math::BigRat';

    if (@_ == 1 &amp;&amp; ref($_[0]) ne 'HASH') {
        my $cfg = $class-&gt;SUPER::config();
        return $cfg-&gt;{$_[0]};
    }

    my $cfg = $class-&gt;SUPER::config(@_);

    # now we need only to override the ones that are different from our parent
    $cfg-&gt;{class} = $class;
    $cfg-&gt;{with}  = $LIB;

    $cfg;
}

###############################################################################
# String conversion methods
###############################################################################

sub bstr {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf'; # -inf, NaN
        return 'inf';                                  # +inf
    }

    # Upgrade?

    return $upgrade -&gt; bstr($x, @r)
      if defined($upgrade) &amp;&amp; !$x -&gt; isa($class);

    # Finite number

    my $s = '';
    $s = $x-&gt;{sign} if $x-&gt;{sign} ne '+';       # '+3/2' =&gt; '3/2'

    my $str = $x-&gt;{sign} eq '-' ? '-' : '';
    $str .= $LIB-&gt;_str($x-&gt;{_n});
    $str .= '/' . $LIB-&gt;_str($x-&gt;{_d}) unless $LIB -&gt; _is_one($x-&gt;{_d});
    return $str;
}

sub bsstr {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    # Upgrade?

    return $upgrade -&gt; bsstr($x, @r)
      if defined($upgrade) &amp;&amp; !$x -&gt; isa($class);

    # Finite number

    my $str = $x-&gt;{sign} eq '-' ? '-' : '';
    $str .= $LIB-&gt;_str($x-&gt;{_n});
    $str .= '/' . $LIB-&gt;_str($x-&gt;{_d}) unless $LIB -&gt; _is_one($x-&gt;{_d});
    return $str;
}

sub bfstr {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    # Upgrade?

    return $upgrade -&gt; bfstr($x, @r)
      if defined($upgrade) &amp;&amp; !$x -&gt; isa($class);

    # Finite number

    my $str = $x-&gt;{sign} eq '-' ? '-' : '';
    $str .= $LIB-&gt;_str($x-&gt;{_n});
    $str .= '/' . $LIB-&gt;_str($x-&gt;{_d}) unless $LIB -&gt; _is_one($x-&gt;{_d});
    return $str;
}

sub bnorm {
    # reduce the number to the shortest form
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Both parts must be objects of whatever we are using today.
    if (my $c = $LIB-&gt;_check($x-&gt;{_n})) {
        croak("n did not pass the self-check ($c) in bnorm()");
    }
    if (my $c = $LIB-&gt;_check($x-&gt;{_d})) {
        croak("d did not pass the self-check ($c) in bnorm()");
    }

    # no normalize for NaN, inf etc.
    if ($x-&gt;{sign} !~ /^[+-]$/) {
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    # normalize zeros to 0/1
    if ($LIB-&gt;_is_zero($x-&gt;{_n})) {
        return $downgrade -&gt; bzero() if defined($downgrade);
        $x-&gt;{sign} = '+';                               # never leave a -0
        $x-&gt;{_d} = $LIB-&gt;_one() unless $LIB-&gt;_is_one($x-&gt;{_d});
        return $x;
    }

    # n/1
    if ($LIB-&gt;_is_one($x-&gt;{_d})) {
        return $downgrade -&gt; new($x) if defined($downgrade);
        return $x;               # no need to reduce
    }

    # Compute the GCD.
    my $gcd = $LIB-&gt;_gcd($LIB-&gt;_copy($x-&gt;{_n}), $x-&gt;{_d});
    if (!$LIB-&gt;_is_one($gcd)) {
        $x-&gt;{_n} = $LIB-&gt;_div($x-&gt;{_n}, $gcd);
        $x-&gt;{_d} = $LIB-&gt;_div($x-&gt;{_d}, $gcd);
    }

    $x;
}

##############################################################################
# sign manipulation

sub bneg {
    # (BRAT or num_str) return BRAT
    # negate number or make a negated number from string
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x if $x-&gt;modify('bneg');

    # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN'
    $x-&gt;{sign} =~ tr/+-/-+/
      unless ($x-&gt;{sign} eq '+' &amp;&amp; $LIB-&gt;_is_zero($x-&gt;{_n}));

    return $downgrade -&gt; new($x)
      if defined($downgrade) &amp;&amp; $LIB -&gt; _is_one($x-&gt;{_d});
    $x;
}

##############################################################################
# mul/add/div etc

sub badd {
    # add two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    unless ($x -&gt; is_finite() &amp;&amp; $y -&gt; is_finite()) {
        if ($x -&gt; is_nan() || $y -&gt; is_nan()) {
            return $x -&gt; bnan(@r);
        } elsif ($x -&gt; is_inf("+")) {
            return $x -&gt; bnan(@r) if $y -&gt; is_inf("-");
            return $x -&gt; binf("+", @r);
        } elsif ($x -&gt; is_inf("-")) {
            return $x -&gt; bnan(@r) if $y -&gt; is_inf("+");
            return $x -&gt; binf("-", @r);
        } elsif ($y -&gt; is_inf("+")) {
            return $x -&gt; binf("+", @r);
        } elsif ($y -&gt; is_inf("-")) {
            return $x -&gt; binf("-", @r);
        }
    }

    #  1   1    gcd(3, 4) = 1    1*3 + 1*4    7
    #  - + -                  = --------- = --
    #  4   3                      4*3       12

    # we do not compute the gcd() here, but simple do:
    #  5   7    5*3 + 7*4   43
    #  - + -  = --------- = --
    #  4   3       4*3      12

    # and bnorm() will then take care of the rest

    # 5 * 3
    $x-&gt;{_n} = $LIB-&gt;_mul($x-&gt;{_n}, $y-&gt;{_d});

    # 7 * 4
    my $m = $LIB-&gt;_mul($LIB-&gt;_copy($y-&gt;{_n}), $x-&gt;{_d});

    # 5 * 3 + 7 * 4
    ($x-&gt;{_n}, $x-&gt;{sign}) = $LIB -&gt; _sadd($x-&gt;{_n}, $x-&gt;{sign}, $m, $y-&gt;{sign});

    # 4 * 3
    $x-&gt;{_d} = $LIB-&gt;_mul($x-&gt;{_d}, $y-&gt;{_d});

    # normalize result, and possible round
    $x-&gt;bnorm()-&gt;round(@r);
}

sub bsub {
    # subtract two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # flip sign of $x, call badd(), then flip sign of result
    $x-&gt;{sign} =~ tr/+-/-+/
      unless $x-&gt;{sign} eq '+' &amp;&amp; $x -&gt; is_zero();      # not -0
    $x = $x-&gt;badd($y, @r);           # does norm and round
    $x-&gt;{sign} =~ tr/+-/-+/
      unless $x-&gt;{sign} eq '+' &amp;&amp; $x -&gt; is_zero();      # not -0

    $x-&gt;bnorm();
}

sub bmul {
    # multiply two rational numbers

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x-&gt;bnan() if $x-&gt;{sign} eq 'NaN' || $y-&gt;{sign} eq 'NaN';

    # inf handling
    if ($x-&gt;{sign} =~ /^[+-]inf$/ || $y-&gt;{sign} =~ /^[+-]inf$/) {
        return $x-&gt;bnan() if $x-&gt;is_zero() || $y-&gt;is_zero();
        # result will always be +-inf:
        # +inf * +/+inf =&gt; +inf, -inf * -/-inf =&gt; +inf
        # +inf * -/-inf =&gt; -inf, -inf * +/+inf =&gt; -inf
        return $x-&gt;binf() if ($x-&gt;{sign} =~ /^\+/ &amp;&amp; $y-&gt;{sign} =~ /^\+/);
        return $x-&gt;binf() if ($x-&gt;{sign} =~ /^-/ &amp;&amp; $y-&gt;{sign} =~ /^-/);
        return $x-&gt;binf('-');
    }

    # x == 0  # also: or y == 1 or y == -1
    if ($x -&gt; is_zero()) {
        $x = $downgrade -&gt; bzero($x) if defined $downgrade;
        return wantarray ? ($x, $class-&gt;bzero()) : $x;
    }

    if ($y -&gt; is_zero()) {
        $x = defined($downgrade) ? $downgrade -&gt; bzero($x) : $x -&gt; bzero();
        return wantarray ? ($x, $class-&gt;bzero()) : $x;
    }

    # According to Knuth, this can be optimized by doing gcd twice (for d
    # and n) and reducing in one step. This saves us a bnorm() at the end.
    #
    # p   s    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
    # - * -  = ----- =  ---------------------------------
    # q   r    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

    my $gcd_pr = $LIB -&gt; _gcd($LIB -&gt; _copy($x-&gt;{_n}), $y-&gt;{_d});
    my $gcd_sq = $LIB -&gt; _gcd($LIB -&gt; _copy($y-&gt;{_n}), $x-&gt;{_d});

    $x-&gt;{_n} = $LIB -&gt; _mul(scalar $LIB -&gt; _div($x-&gt;{_n}, $gcd_pr),
                            scalar $LIB -&gt; _div($LIB -&gt; _copy($y-&gt;{_n}),
                                                $gcd_sq));
    $x-&gt;{_d} = $LIB -&gt; _mul(scalar $LIB -&gt; _div($x-&gt;{_d}, $gcd_sq),
                            scalar $LIB -&gt; _div($LIB -&gt; _copy($y-&gt;{_d}),
                                                $gcd_pr));

    # compute new sign
    $x-&gt;{sign} = $x-&gt;{sign} eq $y-&gt;{sign} ? '+' : '-';

    $x-&gt;bnorm()-&gt;round(@r);
}

sub bdiv {
    # (dividend: BRAT or num_str, divisor: BRAT or num_str) return
    # (BRAT, BRAT) (quo, rem) or BRAT (only rem)

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x-&gt;modify('bdiv');

    my $wantarray = wantarray;  # call only once

    # At least one argument is NaN. This is handled the same way as in
    # Math::BigInt -&gt; bdiv(). See the comments in the code implementing that
    # method.

    if ($x -&gt; is_nan() || $y -&gt; is_nan()) {
        if ($wantarray) {
            return $downgrade -&gt; bnan(), $downgrade -&gt; bnan()
              if defined($downgrade);
            return $x -&gt; bnan(), $class -&gt; bnan();
        } else {
            return $downgrade -&gt; bnan()
              if defined($downgrade);
            return $x -&gt; bnan();
        }
    }

    # Divide by zero and modulo zero. This is handled the same way as in
    # Math::BigInt -&gt; bdiv(). See the comments in the code implementing that
    # method.

    if ($y -&gt; is_zero()) {
        my ($quo, $rem);
        if ($wantarray) {
            $rem = $x -&gt; copy();
        }
        if ($x -&gt; is_zero()) {
            $quo = $x -&gt; bnan();
        } else {
            $quo = $x -&gt; binf($x -&gt; {sign});
        }

        $quo = $downgrade -&gt; new($quo)
          if defined($downgrade) &amp;&amp; $quo -&gt; is_int();
        $rem = $downgrade -&gt; new($rem)
          if $wantarray &amp;&amp; defined($downgrade) &amp;&amp; $rem -&gt; is_int();
        return $wantarray ? ($quo, $rem) : $quo;
    }

    # Numerator (dividend) is +/-inf. This is handled the same way as in
    # Math::BigInt -&gt; bdiv(). See the comments in the code implementing that
    # method.

    if ($x -&gt; is_inf()) {
        my ($quo, $rem);
        $rem = $class -&gt; bnan() if $wantarray;
        if ($y -&gt; is_inf()) {
            $quo = $x -&gt; bnan();
        } else {
            my $sign = $x -&gt; bcmp(0) == $y -&gt; bcmp(0) ? '+' : '-';
            $quo = $x -&gt; binf($sign);
        }

        $quo = $downgrade -&gt; new($quo)
          if defined($downgrade) &amp;&amp; $quo -&gt; is_int();
        $rem = $downgrade -&gt; new($rem)
          if $wantarray &amp;&amp; defined($downgrade) &amp;&amp; $rem -&gt; is_int();
        return $wantarray ? ($quo, $rem) : $quo;
    }

    # Denominator (divisor) is +/-inf. This is handled the same way as in
    # Math::BigFloat -&gt; bdiv(). See the comments in the code implementing that
    # method.

    if ($y -&gt; is_inf()) {
        my ($quo, $rem);
        if ($wantarray) {
            if ($x -&gt; is_zero() || $x -&gt; bcmp(0) == $y -&gt; bcmp(0)) {
                $rem = $x -&gt; copy();
                $quo = $x -&gt; bzero();
            } else {
                $rem = $class -&gt; binf($y -&gt; {sign});
                $quo = $x -&gt; bone('-');
            }
            $quo = $downgrade -&gt; new($quo)
              if defined($downgrade) &amp;&amp; $quo -&gt; is_int();
            $rem = $downgrade -&gt; new($rem)
              if defined($downgrade) &amp;&amp; $rem -&gt; is_int();
            return ($quo, $rem);
        } else {
            if ($y -&gt; is_inf()) {
                if ($x -&gt; is_nan() || $x -&gt; is_inf()) {
                    return $downgrade -&gt; bnan() if defined $downgrade;
                    return $x -&gt; bnan();
                } else {
                    return $downgrade -&gt; bzero() if defined $downgrade;
                    return $x -&gt; bzero();
                }
            }
        }
    }

    # At this point, both the numerator and denominator are finite numbers, and
    # the denominator (divisor) is non-zero.

    # x == 0?
    if ($x-&gt;is_zero()) {
        return $wantarray ? ($downgrade -&gt; bzero(), $downgrade -&gt; bzero())
                          : $downgrade -&gt; bzero() if defined $downgrade;
        return $wantarray ? ($x, $class-&gt;bzero()) : $x;
    }

    # XXX TODO: list context, upgrade
    # According to Knuth, this can be optimized by doing gcd twice (for d and n)
    # and reducing in one step. This would save us the bnorm() at the end.
    #
    # p   r    p * s    (p / gcd(p, r)) * (s / gcd(s, q))
    # - / -  = ----- =  ---------------------------------
    # q   s    q * r    (q / gcd(s, q)) * (r / gcd(p, r))

    $x-&gt;{_n} = $LIB-&gt;_mul($x-&gt;{_n}, $y-&gt;{_d});
    $x-&gt;{_d} = $LIB-&gt;_mul($x-&gt;{_d}, $y-&gt;{_n});

    # compute new sign
    $x-&gt;{sign} = $x-&gt;{sign} eq $y-&gt;{sign} ? '+' : '-';

    $x -&gt; bnorm();
    if (wantarray) {
        my $rem = $x -&gt; copy();
        $x = $x -&gt; bfloor();
        $x = $x -&gt; round(@r);
        $rem = $rem -&gt; bsub($x -&gt; copy()) -&gt; bmul($y);
        $x   = $downgrade -&gt; new($x)   if defined($downgrade) &amp;&amp; $x -&gt; is_int();
        $rem = $downgrade -&gt; new($rem) if defined($downgrade) &amp;&amp; $rem -&gt; is_int();
        return $x, $rem;
    } else {
        return $x -&gt; round(@r);
    }
}

sub bmod {
    # compute "remainder" (in Perl way) of $x / $y

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x-&gt;modify('bmod');

    # At least one argument is NaN. This is handled the same way as in
    # Math::BigInt -&gt; bmod().

    if ($x -&gt; is_nan() || $y -&gt; is_nan()) {
        return $x -&gt; bnan();
    }

    # Modulo zero. This is handled the same way as in Math::BigInt -&gt; bmod().

    if ($y -&gt; is_zero()) {
        return $downgrade -&gt; bzero() if defined $downgrade;
        return $x;
    }

    # Numerator (dividend) is +/-inf. This is handled the same way as in
    # Math::BigInt -&gt; bmod().

    if ($x -&gt; is_inf()) {
        return $x -&gt; bnan();
    }

    # Denominator (divisor) is +/-inf. This is handled the same way as in
    # Math::BigInt -&gt; bmod().

    if ($y -&gt; is_inf()) {
        if ($x -&gt; is_zero() || $x -&gt; bcmp(0) == $y -&gt; bcmp(0)) {
            return $downgrade -&gt; new($x) if defined($downgrade) &amp;&amp; $x -&gt; is_int();
            return $x;
        } else {
            return $downgrade -&gt; binf($y -&gt; sign()) if defined($downgrade);
            return $x -&gt; binf($y -&gt; sign());
        }
    }

    # At this point, both the numerator and denominator are finite numbers, and
    # the denominator (divisor) is non-zero.

    if ($x-&gt;is_zero()) {        # 0 / 7 = 0, mod 0
        return $downgrade -&gt; bzero() if defined $downgrade;
        return $x;
    }

    # Compute $x - $y * floor($x/$y). This can probably be optimized by working
    # on a lower level.

    $x -&gt; bsub($x -&gt; copy() -&gt; bdiv($y) -&gt; bfloor() -&gt; bmul($y));
    return $x -&gt; round(@r);
}

##############################################################################
# bdec/binc

sub bdec {
    # decrement value (subtract 1)
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    if ($x-&gt;{sign} !~ /^[+-]$/) {       # NaN, inf, -inf
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    if ($x-&gt;{sign} eq '-') {
        $x-&gt;{_n} = $LIB-&gt;_add($x-&gt;{_n}, $x-&gt;{_d}); # -5/2 =&gt; -7/2
    } else {
        if ($LIB-&gt;_acmp($x-&gt;{_n}, $x-&gt;{_d}) &lt; 0) # n &lt; d?
        {
            # 1/3 -- =&gt; -2/3
            $x-&gt;{_n} = $LIB-&gt;_sub($LIB-&gt;_copy($x-&gt;{_d}), $x-&gt;{_n});
            $x-&gt;{sign} = '-';
        } else {
            $x-&gt;{_n} = $LIB-&gt;_sub($x-&gt;{_n}, $x-&gt;{_d}); # 5/2 =&gt; 3/2
        }
    }
    $x-&gt;bnorm()-&gt;round(@r);
}

sub binc {
    # increment value (add 1)
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    if ($x-&gt;{sign} !~ /^[+-]$/) {       # NaN, inf, -inf
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    if ($x-&gt;{sign} eq '-') {
        if ($LIB-&gt;_acmp($x-&gt;{_n}, $x-&gt;{_d}) &lt; 0) {
            # -1/3 ++ =&gt; 2/3 (overflow at 0)
            $x-&gt;{_n} = $LIB-&gt;_sub($LIB-&gt;_copy($x-&gt;{_d}), $x-&gt;{_n});
            $x-&gt;{sign} = '+';
        } else {
            $x-&gt;{_n} = $LIB-&gt;_sub($x-&gt;{_n}, $x-&gt;{_d}); # -5/2 =&gt; -3/2
        }
    } else {
        $x-&gt;{_n} = $LIB-&gt;_add($x-&gt;{_n}, $x-&gt;{_d}); # 5/2 =&gt; 7/2
    }
    $x-&gt;bnorm()-&gt;round(@r);
}

sub binv {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    return $x if $x -&gt; modify('binv');

    return $x -&gt; round(@r)     if $x -&gt; is_nan();
    return $x -&gt; bzero(@r)     if $x -&gt; is_inf();
    return $x -&gt; binf("+", @r) if $x -&gt; is_zero();

    ($x -&gt; {_n}, $x -&gt; {_d}) = ($x -&gt; {_d}, $x -&gt; {_n});
    $x -&gt; round(@r);
}

##############################################################################
# is_foo methods (the rest is inherited)

sub is_int {
    # return true if arg (BRAT or num_str) is an integer
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if ($x-&gt;{sign} =~ /^[+-]$/) &amp;&amp; # NaN and +-inf aren't
      $LIB-&gt;_is_one($x-&gt;{_d});              # x/y &amp;&amp; y != 1 =&gt; no integer
    0;
}

sub is_zero {
    # return true if arg (BRAT or num_str) is zero
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if $x-&gt;{sign} eq '+' &amp;&amp; $LIB-&gt;_is_zero($x-&gt;{_n});
    0;
}

sub is_one {
    # return true if arg (BRAT or num_str) is +1 or -1 if signis given
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    croak "too many arguments for is_one()" if @_ &gt; 2;
    my $sign = $_[1] || '';
    $sign = '+' if $sign ne '-';
    return 1 if ($x-&gt;{sign} eq $sign &amp;&amp;
                 $LIB-&gt;_is_one($x-&gt;{_n}) &amp;&amp; $LIB-&gt;_is_one($x-&gt;{_d}));
    0;
}

sub is_odd {
    # return true if arg (BFLOAT or num_str) is odd or false if even
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 1 if ($x-&gt;{sign} =~ /^[+-]$/) &amp;&amp;               # NaN &amp; +-inf aren't
      ($LIB-&gt;_is_one($x-&gt;{_d}) &amp;&amp; $LIB-&gt;_is_odd($x-&gt;{_n})); # x/2 is not, but 3/1
    0;
}

sub is_even {
    # return true if arg (BINT or num_str) is even or false if odd
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return 0 if $x-&gt;{sign} !~ /^[+-]$/; # NaN &amp; +-inf aren't
    return 1 if ($LIB-&gt;_is_one($x-&gt;{_d}) # x/3 is never
                 &amp;&amp; $LIB-&gt;_is_even($x-&gt;{_n})); # but 4/1 is
    0;
}

##############################################################################
# parts() and friends

sub numerator {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    # NaN, inf, -inf
    return Math::BigInt-&gt;new($x-&gt;{sign}) if ($x-&gt;{sign} !~ /^[+-]$/);

    my $n = Math::BigInt-&gt;new($LIB-&gt;_str($x-&gt;{_n}));
    $n-&gt;{sign} = $x-&gt;{sign};
    $n;
}

sub denominator {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    # NaN
    return Math::BigInt-&gt;new($x-&gt;{sign}) if $x-&gt;{sign} eq 'NaN';
    # inf, -inf
    return Math::BigInt-&gt;bone() if $x-&gt;{sign} !~ /^[+-]$/;

    Math::BigInt-&gt;new($LIB-&gt;_str($x-&gt;{_d}));
}

sub parts {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    my $c = 'Math::BigInt';

    return ($c-&gt;bnan(), $c-&gt;bnan()) if $x-&gt;{sign} eq 'NaN';
    return ($c-&gt;binf(), $c-&gt;binf()) if $x-&gt;{sign} eq '+inf';
    return ($c-&gt;binf('-'), $c-&gt;binf()) if $x-&gt;{sign} eq '-inf';

    my $n = $c-&gt;new($LIB-&gt;_str($x-&gt;{_n}));
    $n-&gt;{sign} = $x-&gt;{sign};
    my $d = $c-&gt;new($LIB-&gt;_str($x-&gt;{_d}));
    ($n, $d);
}

sub dparts {
    my $x = shift;
    my $class = ref $x;

    croak("dparts() is an instance method") unless $class;

    if ($x -&gt; is_nan()) {
        return $class -&gt; bnan(), $class -&gt; bnan() if wantarray;
        return $class -&gt; bnan();
    }

    if ($x -&gt; is_inf()) {
        return $class -&gt; binf($x -&gt; sign()), $class -&gt; bzero() if wantarray;
        return $class -&gt; binf($x -&gt; sign());
    }

    # 355/113 =&gt; 3 + 16/113

    my ($q, $r)  = $LIB -&gt; _div($LIB -&gt; _copy($x -&gt; {_n}), $x -&gt; {_d});

    my $int = Math::BigRat -&gt; new($x -&gt; {sign} . $LIB -&gt; _str($q));
    return $int unless wantarray;

    my $frc = Math::BigRat -&gt; new($x -&gt; {sign} . $LIB -&gt; _str($r),
                                  $LIB -&gt; _str($x -&gt; {_d}));

    return $int, $frc;
}

sub fparts {
    my $x = shift;
    my $class = ref $x;

    croak("fparts() is an instance method") unless $class;

    return ($class -&gt; bnan(),
            $class -&gt; bnan()) if $x -&gt; is_nan();

    my $numer = $x -&gt; copy();
    my $denom = $class -&gt; bzero();

    $denom -&gt; {_n} = $numer -&gt; {_d};
    $numer -&gt; {_d} = $LIB -&gt; _one();

    return ($numer, $denom);
}

sub length {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $nan unless $x-&gt;is_int();
    $LIB-&gt;_len($x-&gt;{_n});       # length(-123/1) =&gt; length(123)
}

sub digit {
    my ($class, $x, $n) = ref($_[0]) ? (undef, $_[0], $_[1]) : objectify(1, @_);

    return $nan unless $x-&gt;is_int();
    $LIB-&gt;_digit($x-&gt;{_n}, $n || 0); # digit(-123/1, 2) =&gt; digit(123, 2)
}

##############################################################################
# special calc routines

sub bceil {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x-&gt;{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB-&gt;_is_one($x-&gt;{_d}))      # integer
    {
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    $x-&gt;{_n} = $LIB-&gt;_div($x-&gt;{_n}, $x-&gt;{_d});  # 22/7 =&gt; 3/1 w/ truncate
    $x-&gt;{_d} = $LIB-&gt;_one();                    # d =&gt; 1
    $x-&gt;{_n} = $LIB-&gt;_inc($x-&gt;{_n}) if $x-&gt;{sign} eq '+';   # +22/7 =&gt; 4/1
    $x-&gt;{sign} = '+' if $x-&gt;{sign} eq '-' &amp;&amp; $LIB-&gt;_is_zero($x-&gt;{_n}); # -0 =&gt; 0
    return $downgrade -&gt; new($x) if defined $downgrade;
    $x;
}

sub bfloor {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x-&gt;{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB-&gt;_is_one($x-&gt;{_d}))      # integer
    {
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    $x-&gt;{_n} = $LIB-&gt;_div($x-&gt;{_n}, $x-&gt;{_d});  # 22/7 =&gt; 3/1 w/ truncate
    $x-&gt;{_d} = $LIB-&gt;_one();                    # d =&gt; 1
    $x-&gt;{_n} = $LIB-&gt;_inc($x-&gt;{_n}) if $x-&gt;{sign} eq '-';   # -22/7 =&gt; -4/1
    return $downgrade -&gt; new($x) if defined $downgrade;
    $x;
}

sub bint {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);

    if ($x-&gt;{sign} !~ /^[+-]$/ ||     # NaN or inf or
        $LIB-&gt;_is_one($x-&gt;{_d}))      # integer
    {
        return $downgrade -&gt; new($x) if defined $downgrade;
        return $x;
    }

    $x-&gt;{_n} = $LIB-&gt;_div($x-&gt;{_n}, $x-&gt;{_d});  # 22/7 =&gt; 3/1 w/ truncate
    $x-&gt;{_d} = $LIB-&gt;_one();                    # d =&gt; 1
    $x-&gt;{sign} = '+' if $x-&gt;{sign} eq '-' &amp;&amp; $LIB -&gt; _is_zero($x-&gt;{_n});
    return $downgrade -&gt; new($x) if defined $downgrade;
    return $x;
}

sub bfac {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    # if $x is not an integer
    if (($x-&gt;{sign} ne '+') || (!$LIB-&gt;_is_one($x-&gt;{_d}))) {
        return $x-&gt;bnan();
    }

    $x-&gt;{_n} = $LIB-&gt;_fac($x-&gt;{_n});
    # since _d is 1, we don't need to reduce/norm the result
    $x-&gt;round(@r);
}

sub bpow {
    # power ($x ** $y)

    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x if $x-&gt;modify('bpow');

    # $x and/or $y is a NaN
    return $x-&gt;bnan() if $x-&gt;is_nan() || $y-&gt;is_nan();

    # $x and/or $y is a +/-Inf
    if ($x-&gt;is_inf("-")) {
        return $x-&gt;bzero()   if $y-&gt;is_negative();
        return $x-&gt;bnan()    if $y-&gt;is_zero();
        return $x            if $y-&gt;is_odd();
        return $x-&gt;bneg();
    } elsif ($x-&gt;is_inf("+")) {
        return $x-&gt;bzero()   if $y-&gt;is_negative();
        return $x-&gt;bnan()    if $y-&gt;is_zero();
        return $x;
    } elsif ($y-&gt;is_inf("-")) {
        return $x-&gt;bnan()    if $x -&gt; is_one("-");
        return $x-&gt;binf("+") if $x &gt; -1 &amp;&amp; $x &lt; 1;
        return $x-&gt;bone()    if $x -&gt; is_one("+");
        return $x-&gt;bzero();
    } elsif ($y-&gt;is_inf("+")) {
        return $x-&gt;bnan()    if $x -&gt; is_one("-");
        return $x-&gt;bzero()   if $x &gt; -1 &amp;&amp; $x &lt; 1;
        return $x-&gt;bone()    if $x -&gt; is_one("+");
        return $x-&gt;binf("+");
    }

    if ($x -&gt; is_zero()) {
        return $x -&gt; bone() if $y -&gt; is_zero();
        return $x -&gt; binf() if $y -&gt; is_negative();
        return $x;
    }

    # We don't support complex numbers, so upgrade or return NaN.

    if ($x -&gt; is_negative() &amp;&amp; !$y -&gt; is_int()) {
        return $upgrade -&gt; bpow($upgrade -&gt; new($x), $y, @r)
          if defined $upgrade;
        return $x -&gt; bnan();
    }

    if ($x -&gt; is_one("+") || $y -&gt; is_one()) {
        return $x;
    }

    if ($x -&gt; is_one("-")) {
        return $x if $y -&gt; is_odd();
        return $x -&gt; bneg();
    }

    # (a/b)^-(c/d) = (b/a)^(c/d)
    ($x-&gt;{_n}, $x-&gt;{_d}) = ($x-&gt;{_d}, $x-&gt;{_n}) if $y-&gt;is_negative();

    unless ($LIB-&gt;_is_one($y-&gt;{_n})) {
        $x-&gt;{_n} = $LIB-&gt;_pow($x-&gt;{_n}, $y-&gt;{_n});
        $x-&gt;{_d} = $LIB-&gt;_pow($x-&gt;{_d}, $y-&gt;{_n});
        $x-&gt;{sign} = '+' if $x-&gt;{sign} eq '-' &amp;&amp; $LIB-&gt;_is_even($y-&gt;{_n});
    }

    unless ($LIB-&gt;_is_one($y-&gt;{_d})) {
        return $x-&gt;bsqrt(@r) if $LIB-&gt;_is_two($y-&gt;{_d}); # 1/2 =&gt; sqrt
        return $x-&gt;broot($LIB-&gt;_str($y-&gt;{_d}), @r);      # 1/N =&gt; root(N)
    }

    return $x-&gt;round(@r);
}

sub blog {
    # Return the logarithm of the operand. If a second operand is defined, that
    # value is used as the base, otherwise the base is assumed to be Euler's
    # constant.

    my ($class, $x, $base, @r);

    # Don't objectify the base, since an undefined base, as in $x-&gt;blog() or
    # $x-&gt;blog(undef) signals that the base is Euler's number.

    if (!ref($_[0]) &amp;&amp; $_[0] =~ /^[A-Za-z]|::/) {
        # E.g., Math::BigRat-&gt;blog(256, 2)
        ($class, $x, $base, @r) =
          defined $_[2] ? objectify(2, @_) : objectify(1, @_);
    } else {
        # E.g., Math::BigRat::blog(256, 2) or $x-&gt;blog(2)
        ($class, $x, $base, @r) =
          defined $_[1] ? objectify(2, @_) : objectify(1, @_);
    }

    return $x if $x-&gt;modify('blog');

    # Handle all exception cases and all trivial cases. I have used Wolfram Alpha
    # (http://www.wolframalpha.com) as the reference for these cases.

    return $x -&gt; bnan() if $x -&gt; is_nan();

    if (defined $base) {
        $base = $class -&gt; new($base) unless ref $base;
        if ($base -&gt; is_nan() || $base -&gt; is_one()) {
            return $x -&gt; bnan();
        } elsif ($base -&gt; is_inf() || $base -&gt; is_zero()) {
            return $x -&gt; bnan() if $x -&gt; is_inf() || $x -&gt; is_zero();
            return $x -&gt; bzero();
        } elsif ($base -&gt; is_negative()) {        # -inf &lt; base &lt; 0
            return $x -&gt; bzero() if $x -&gt; is_one(); #     x = 1
            return $x -&gt; bone()  if $x == $base;    #     x = base
            return $x -&gt; bnan();                    #     otherwise
        }
        return $x -&gt; bone() if $x == $base; # 0 &lt; base &amp;&amp; 0 &lt; x &lt; inf
    }

    # We now know that the base is either undefined or positive and finite.

    if ($x -&gt; is_inf()) {       # x = +/-inf
        my $sign = defined $base &amp;&amp; $base &lt; 1 ? '-' : '+';
        return $x -&gt; binf($sign);
    } elsif ($x -&gt; is_neg()) {  # -inf &lt; x &lt; 0
        return $x -&gt; bnan();
    } elsif ($x -&gt; is_one()) {  # x = 1
        return $x -&gt; bzero();
    } elsif ($x -&gt; is_zero()) { # x = 0
        my $sign = defined $base &amp;&amp; $base &lt; 1 ? '+' : '-';
        return $x -&gt; binf($sign);
    }

    # Now take care of the cases where $x and/or $base is 1/N.
    #
    #   log(1/N) / log(B)   = -log(N)/log(B)
    #   log(1/N) / log(1/B) =  log(N)/log(B)
    #   log(N)   / log(1/B) = -log(N)/log(B)

    my $neg = 0;
    if ($x -&gt; numerator() -&gt; is_one()) {
        $x -&gt; binv();
        $neg = !$neg;
    }
    if (defined(blessed($base)) &amp;&amp; $base -&gt; isa($class)) {
        if ($base -&gt; numerator() -&gt; is_one()) {
            $base = $base -&gt; copy() -&gt; binv();
            $neg = !$neg;
        }
    }

    # disable upgrading and downgrading

    require Math::BigFloat;
    my $upg = Math::BigFloat -&gt; upgrade();
    my $dng = Math::BigFloat -&gt; downgrade();
    Math::BigFloat -&gt; upgrade(undef);
    Math::BigFloat -&gt; downgrade(undef);

    # At this point we are done handling all exception cases and trivial cases.

    $base = Math::BigFloat -&gt; new($base) if defined $base;
    my $xnum = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_n}));
    my $xden = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_d}));
    my $xstr = $xnum -&gt; bdiv($xden) -&gt; blog($base, @r) -&gt; bsstr();

    # reset upgrading and downgrading

    Math::BigFloat -&gt; upgrade($upg);
    Math::BigFloat -&gt; downgrade($dng);

    my $xobj = Math::BigRat -&gt; new($xstr);
    $x -&gt; {sign} = $xobj -&gt; {sign};
    $x -&gt; {_n}   = $xobj -&gt; {_n};
    $x -&gt; {_d}   = $xobj -&gt; {_d};

    return $neg ? $x -&gt; bneg() : $x;
}

sub bexp {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(1, @_);
    }

    return $x-&gt;binf(@r)  if $x-&gt;{sign} eq '+inf';
    return $x-&gt;bzero(@r) if $x-&gt;{sign} eq '-inf';

    # we need to limit the accuracy to protect against overflow
    my $fallback = 0;
    my ($scale, @params);
    ($x, @params) = $x-&gt;_find_round_parameters(@r);

    # also takes care of the "error in _find_round_parameters?" case
    return $x if $x-&gt;{sign} eq 'NaN';

    # no rounding at all, so must use fallback
    if (scalar @params == 0) {
        # simulate old behaviour
        $params[0] = $class-&gt;div_scale(); # and round to it as accuracy
        $params[1] = undef;              # P = undef
        $scale = $params[0]+4;           # at least four more for proper round
        $params[2] = $r[2];              # round mode by caller or undef
        $fallback = 1;                   # to clear a/p afterwards
    } else {
        # the 4 below is empirical, and there might be cases where it's not enough...
        $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined
    }

    return $x-&gt;bone(@params) if $x-&gt;is_zero();

    # See the comments in Math::BigFloat on how this algorithm works.
    # Basically we calculate A and B (where B is faculty(N)) so that A/B = e

    my $x_org = $x-&gt;copy();
    if ($scale &lt;= 75) {
        # set $x directly from a cached string form
        $x-&gt;{_n} =
          $LIB-&gt;_new("90933395208605785401971970164779391644753259799242");
        $x-&gt;{_d} =
          $LIB-&gt;_new("33452526613163807108170062053440751665152000000000");
        $x-&gt;{sign} = '+';
    } else {
        # compute A and B so that e = A / B.

        # After some terms we end up with this, so we use it as a starting point:
        my $A = $LIB-&gt;_new("90933395208605785401971970164779391644753259799242");
        my $F = $LIB-&gt;_new(42); my $step = 42;

        # Compute how many steps we need to take to get $A and $B sufficiently big
        my $steps = Math::BigFloat::_len_to_steps($scale - 4);
        #    print STDERR "# Doing $steps steps for ", $scale-4, " digits\n";
        while ($step++ &lt;= $steps) {
            # calculate $a * $f + 1
            $A = $LIB-&gt;_mul($A, $F);
            $A = $LIB-&gt;_inc($A);
            # increment f
            $F = $LIB-&gt;_inc($F);
        }
        # compute $B as factorial of $steps (this is faster than doing it manually)
        my $B = $LIB-&gt;_fac($LIB-&gt;_new($steps));

        #  print "A ", $LIB-&gt;_str($A), "\nB ", $LIB-&gt;_str($B), "\n";

        $x-&gt;{_n} = $A;
        $x-&gt;{_d} = $B;
        $x-&gt;{sign} = '+';
    }

    # $x contains now an estimate of e, with some surplus digits, so we can round
    if (!$x_org-&gt;is_one()) {
        # raise $x to the wanted power and round it in one step:
        $x-&gt;bpow($x_org, @params);
    } else {
        # else just round the already computed result
        delete $x-&gt;{accuracy}; delete $x-&gt;{precision};
        # shortcut to not run through _find_round_parameters again
        if (defined $params[0]) {
            $x-&gt;bround($params[0], $params[2]); # then round accordingly
        } else {
            $x-&gt;bfround($params[1], $params[2]); # then round accordingly
        }
    }
    if ($fallback) {
        # clear a/p after round, since user did not request it
        delete $x-&gt;{accuracy}; delete $x-&gt;{precision};
    }

    $x;
}

sub bnok {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    return $x-&gt;bnan() if $x-&gt;is_nan() || $y-&gt;is_nan();
    return $x-&gt;bnan() if (($x-&gt;is_finite() &amp;&amp; !$x-&gt;is_int()) ||
                          ($y-&gt;is_finite() &amp;&amp; !$y-&gt;is_int()));

    my $xint = Math::BigInt -&gt; new($x -&gt; bstr());
    my $yint = Math::BigInt -&gt; new($y -&gt; bstr());
    $xint -&gt; bnok($yint);
    my $xrat = Math::BigRat -&gt; new($xint);

    $x -&gt; {sign} = $xrat -&gt; {sign};
    $x -&gt; {_n}   = $xrat -&gt; {_n};
    $x -&gt; {_d}   = $xrat -&gt; {_d};

    return $x;
}

sub broot {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # Convert $x into a Math::BigFloat.

    my $xd   = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_d}));
    my $xflt = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_n})) -&gt; bdiv($xd);
    $xflt -&gt; {sign} = $x -&gt; {sign};

    # Convert $y into a Math::BigFloat.

    my $yd   = Math::BigFloat -&gt; new($LIB -&gt; _str($y-&gt;{_d}));
    my $yflt = Math::BigFloat -&gt; new($LIB -&gt; _str($y-&gt;{_n})) -&gt; bdiv($yd);
    $yflt -&gt; {sign} = $y -&gt; {sign};

    # Compute the root and convert back to a Math::BigRat.

    $xflt -&gt; broot($yflt, @r);
    my $xtmp = Math::BigRat -&gt; new($xflt -&gt; bsstr());

    $x -&gt; {sign} = $xtmp -&gt; {sign};
    $x -&gt; {_n}   = $xtmp -&gt; {_n};
    $x -&gt; {_d}   = $xtmp -&gt; {_d};

    return $x;
}

sub bmodpow {
    # set up parameters
    my ($class, $x, $y, $m, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, $m, @r) = objectify(3, @_);
    }

    # Convert $x, $y, and $m into Math::BigInt objects.

    my $xint = Math::BigInt -&gt; new($x -&gt; copy() -&gt; bint());
    my $yint = Math::BigInt -&gt; new($y -&gt; copy() -&gt; bint());
    my $mint = Math::BigInt -&gt; new($m -&gt; copy() -&gt; bint());

    $xint -&gt; bmodpow($yint, $mint, @r);
    my $xtmp = Math::BigRat -&gt; new($xint -&gt; bsstr());

    $x -&gt; {sign} = $xtmp -&gt; {sign};
    $x -&gt; {_n}   = $xtmp -&gt; {_n};
    $x -&gt; {_d}   = $xtmp -&gt; {_d};
    return $x;
}

sub bmodinv {
    # set up parameters
    my ($class, $x, $y, @r) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y, @r) = objectify(2, @_);
    }

    # Convert $x and $y into Math::BigInt objects.

    my $xint = Math::BigInt -&gt; new($x -&gt; copy() -&gt; bint());
    my $yint = Math::BigInt -&gt; new($y -&gt; copy() -&gt; bint());

    $xint -&gt; bmodinv($yint, @r);
    my $xtmp = Math::BigRat -&gt; new($xint -&gt; bsstr());

    $x -&gt; {sign} = $xtmp -&gt; {sign};
    $x -&gt; {_n}   = $xtmp -&gt; {_n};
    $x -&gt; {_d}   = $xtmp -&gt; {_d};
    return $x;
}

sub bsqrt {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    return $x-&gt;bnan() if $x-&gt;{sign} !~ /^[+]/; # NaN, -inf or &lt; 0
    return $x if $x-&gt;{sign} eq '+inf';         # sqrt(inf) == inf
    return $x-&gt;round(@r) if $x-&gt;is_zero() || $x-&gt;is_one();

    my $n = $x -&gt; {_n};
    my $d = $x -&gt; {_d};

    # Look for an exact solution. For the numerator and the denominator, take
    # the square root and square it and see if we got the original value. If we
    # did, for both the numerator and the denominator, we have an exact
    # solution.

    {
        my $nsqrt = $LIB -&gt; _sqrt($LIB -&gt; _copy($n));
        my $n2    = $LIB -&gt; _mul($LIB -&gt; _copy($nsqrt), $nsqrt);
        if ($LIB -&gt; _acmp($n, $n2) == 0) {
            my $dsqrt = $LIB -&gt; _sqrt($LIB -&gt; _copy($d));
            my $d2    = $LIB -&gt; _mul($LIB -&gt; _copy($dsqrt), $dsqrt);
            if ($LIB -&gt; _acmp($d, $d2) == 0) {
                $x -&gt; {_n} = $nsqrt;
                $x -&gt; {_d} = $dsqrt;
                return $x-&gt;round(@r);
            }
        }
    }

    local $Math::BigFloat::upgrade   = undef;
    local $Math::BigFloat::downgrade = undef;
    local $Math::BigFloat::precision = undef;
    local $Math::BigFloat::accuracy  = undef;
    local $Math::BigInt::upgrade     = undef;
    local $Math::BigInt::precision   = undef;
    local $Math::BigInt::accuracy    = undef;

    my $xn = Math::BigFloat -&gt; new($LIB -&gt; _str($n));
    my $xd = Math::BigFloat -&gt; new($LIB -&gt; _str($d));

    my $xtmp = Math::BigRat -&gt; new($xn -&gt; bdiv($xd) -&gt; bsqrt() -&gt; bsstr());

    $x -&gt; {sign} = $xtmp -&gt; {sign};
    $x -&gt; {_n}   = $xtmp -&gt; {_n};
    $x -&gt; {_d}   = $xtmp -&gt; {_d};

    $x-&gt;round(@r);
}

sub blsft {
    my ($class, $x, $y, $b) = objectify(2, @_);

    $b = 2 if !defined $b;
    $b = $class -&gt; new($b) unless ref($b) &amp;&amp; $b -&gt; isa($class);

    return $x -&gt; bnan() if $x -&gt; is_nan() || $y -&gt; is_nan() || $b -&gt; is_nan();

    # shift by a negative amount?
    return $x -&gt; brsft($y -&gt; copy() -&gt; babs(), $b) if $y -&gt; {sign} =~ /^-/;

    $x -&gt; bmul($b -&gt; bpow($y));
}

sub brsft {
    my ($class, $x, $y, $b) = objectify(2, @_);

    $b = 2 if !defined $b;
    $b = $class -&gt; new($b) unless ref($b) &amp;&amp; $b -&gt; isa($class);

    return $x -&gt; bnan() if $x -&gt; is_nan() || $y -&gt; is_nan() || $b -&gt; is_nan();

    # shift by a negative amount?
    return $x -&gt; blsft($y -&gt; copy() -&gt; babs(), $b) if $y -&gt; {sign} =~ /^-/;

    # the following call to bdiv() will return either quotient (scalar context)
    # or quotient and remainder (list context).
    $x -&gt; bdiv($b -&gt; bpow($y));
}

###############################################################################
# Bitwise methods
###############################################################################

# Bitwise left shift.

sub bblsft {
    # We don't call objectify(), because the bitwise methods should not
    # upgrade/downgrade, even when upgrading/downgrading is enabled.

    my ($class, $x, $y, @r) = ref($_[0]) ? (ref($_[0]), @_) : @_;

    my $xint = Math::BigInt -&gt; bblsft($x, $y, @r);

    # Temporarily disable downgrading.

    my $dng = $class -&gt; downgrade();
    $class -&gt; downgrade(undef);

    # Convert to our class without downgrading.

    my $xrat = $class -&gt; new($xint);

    # Reset downgrading.

    $class -&gt; downgrade($dng);

    # If we are called as a class method, the first operand might not be an
    # object of this class, so check.

    if (defined(blessed($x)) &amp;&amp; $x -&gt; isa(__PACKAGE__)) {
        $x -&gt; {sign} = $xrat -&gt; {sign};
        $x -&gt; {_n}   = $xrat -&gt; {_n};
        $x -&gt; {_d}   = $xrat -&gt; {_d};
    } else {
        $x = $xrat;
    }

    # Now we might downgrade.

    return $downgrade -&gt; new($x) if defined($downgrade);
    $x -&gt; round(@r);
}

# Bitwise right shift.

sub bbrsft {
    # We don't call objectify(), because the bitwise methods should not
    # upgrade/downgrade, even when upgrading/downgrading is enabled.

    my ($class, $x, $y, @r) = ref($_[0]) ? (ref($_[0]), @_) : @_;

    my $xint = Math::BigInt -&gt; bbrsft($x, $y, @r);

    # Temporarily disable downgrading.

    my $dng = $class -&gt; downgrade();
    $class -&gt; downgrade(undef);

    # Convert to our class without downgrading.

    my $xrat = $class -&gt; new($xint);

    # Reset downgrading.

    $class -&gt; downgrade($dng);

    # If we are called as a class method, the first operand might not be an
    # object of this class, so check.

    if (defined(blessed($x)) &amp;&amp; $x -&gt; isa(__PACKAGE__)) {
        $x -&gt; {sign} = $xrat -&gt; {sign};
        $x -&gt; {_n}   = $xrat -&gt; {_n};
        $x -&gt; {_d}   = $xrat -&gt; {_d};
    } else {
        $x = $xrat;
    }

    # Now we might downgrade.

    return $downgrade -&gt; new($x) if defined($downgrade);
    $x -&gt; round(@r);
}

sub band {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'band() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for band()' if @_ &lt; 1;

    my $y = shift;
    $y = $class -&gt; new($y) unless ref($y);

    my @r = @_;

    my $xint = $x -&gt; as_int();          # to Math::BigInt
    my $yint = $y -&gt; as_int();          # to Math::BigInt

    $xint = $xint -&gt; band($yint);

    my $xrat = $class -&gt; new($xint);    # back to Math::BigRat
    $x -&gt; {sign} = $xrat -&gt; {sign};
    $x -&gt; {_n}   = $xrat -&gt; {_n};
    $x -&gt; {_d}   = $xrat -&gt; {_d};

    return $x -&gt; round(@r);
}

sub bior {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bior() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for bior()' if @_ &lt; 1;

    my $y = shift;
    $y = $class -&gt; new($y) unless ref($y);

    my @r = @_;

    my $xint = $x -&gt; as_int();          # to Math::BigInt
    my $yint = $y -&gt; as_int();          # to Math::BigInt

    $xint = $xint -&gt; bior($yint);

    my $xrat = $class -&gt; new($xint);    # back to Math::BigRat
    $x -&gt; {sign} = $xrat -&gt; {sign};
    $x -&gt; {_n}   = $xrat -&gt; {_n};
    $x -&gt; {_d}   = $xrat -&gt; {_d};

    return $x -&gt; round(@r);
}

sub bxor {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bxor() is an instance method, not a class method' unless $xref;
    croak 'Not enough arguments for bxor()' if @_ &lt; 1;

    my $y = shift;
    $y = $class -&gt; new($y) unless ref($y);

    my @r = @_;

    my $xint = $x -&gt; as_int();          # to Math::BigInt
    my $yint = $y -&gt; as_int();          # to Math::BigInt

    $xint = $xint -&gt; bxor($yint);

    my $xrat = $class -&gt; new($xint);    # back to Math::BigRat
    $x -&gt; {sign} = $xrat -&gt; {sign};
    $x -&gt; {_n}   = $xrat -&gt; {_n};
    $x -&gt; {_d}   = $xrat -&gt; {_d};

    return $x -&gt; round(@r);
}

sub bnot {
    my $x     = shift;
    my $xref  = ref($x);
    my $class = $xref || $x;

    croak 'bnot() is an instance method, not a class method' unless $xref;

    my @r = @_;

    my $xint = $x -&gt; as_int();          # to Math::BigInt
    $xint = $xint -&gt; bnot();

    my $xrat = $class -&gt; new($xint);    # back to Math::BigRat
    $x -&gt; {sign} = $xrat -&gt; {sign};
    $x -&gt; {_n}   = $xrat -&gt; {_n};
    $x -&gt; {_d}   = $xrat -&gt; {_d};

    return $x -&gt; round(@r);
}

##############################################################################
# round

sub round {
    my $x = shift;
    return $downgrade -&gt; new($x) if defined($downgrade) &amp;&amp;
      ($x -&gt; is_int() || $x -&gt; is_inf() || $x -&gt; is_nan());
    $x;
}

sub bround {
    my $x = shift;
    return $downgrade -&gt; new($x) if defined($downgrade) &amp;&amp;
      ($x -&gt; is_int() || $x -&gt; is_inf() || $x -&gt; is_nan());
    $x;
}

sub bfround {
    my $x = shift;
    return $downgrade -&gt; new($x) if defined($downgrade) &amp;&amp;
      ($x -&gt; is_int() || $x -&gt; is_inf() || $x -&gt; is_nan());
    $x;
}

##############################################################################
# comparing

sub bcmp {
    # compare two signed numbers

    # set up parameters
    my ($class, $x, $y) = (ref($_[0]), @_);

    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y) = objectify(2, @_);
    }

    if ($x-&gt;{sign} !~ /^[+-]$/ || $y-&gt;{sign} !~ /^[+-]$/) {
        # $x is NaN and/or $y is NaN
        return       if $x-&gt;{sign} eq $nan || $y-&gt;{sign} eq $nan;
        # $x and $y are both either +inf or -inf
        return  0    if $x-&gt;{sign} eq $y-&gt;{sign} &amp;&amp; $x-&gt;{sign} =~ /^[+-]inf$/;
        # $x = +inf and $y &lt; +inf
        return +1    if $x-&gt;{sign} eq '+inf';
        # $x = -inf and $y &gt; -inf
        return -1    if $x-&gt;{sign} eq '-inf';
        # $x &lt; +inf and $y = +inf
        return -1    if $y-&gt;{sign} eq '+inf';
        # $x &gt; -inf and $y = -inf
        return +1;
    }

    # $x &gt;= 0 and $y &lt; 0
    return  1 if $x-&gt;{sign} eq '+' &amp;&amp; $y-&gt;{sign} eq '-';
    # $x &lt; 0 and $y &gt;= 0
    return -1 if $x-&gt;{sign} eq '-' &amp;&amp; $y-&gt;{sign} eq '+';

    # At this point, we know that $x and $y have the same sign.

    # shortcut
    my $xz = $LIB-&gt;_is_zero($x-&gt;{_n});
    my $yz = $LIB-&gt;_is_zero($y-&gt;{_n});
    return  0 if $xz &amp;&amp; $yz;               # 0 &lt;=&gt; 0
    return -1 if $xz &amp;&amp; $y-&gt;{sign} eq '+'; # 0 &lt;=&gt; +y
    return  1 if $yz &amp;&amp; $x-&gt;{sign} eq '+'; # +x &lt;=&gt; 0

    my $t = $LIB-&gt;_mul($LIB-&gt;_copy($x-&gt;{_n}), $y-&gt;{_d});
    my $u = $LIB-&gt;_mul($LIB-&gt;_copy($y-&gt;{_n}), $x-&gt;{_d});

    my $cmp = $LIB-&gt;_acmp($t, $u);     # signs are equal
    $cmp = -$cmp if $x-&gt;{sign} eq '-'; # both are '-' =&gt; reverse
    $cmp;
}

sub bacmp {
    # compare two numbers (as unsigned)

    # set up parameters
    my ($class, $x, $y) = (ref($_[0]), @_);
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y) = objectify(2, @_);
    }

    if (($x-&gt;{sign} !~ /^[+-]$/) || ($y-&gt;{sign} !~ /^[+-]$/)) {
        # handle +-inf and NaN
        return    if (($x-&gt;{sign} eq $nan) || ($y-&gt;{sign} eq $nan));
        return  0 if $x-&gt;{sign} =~ /^[+-]inf$/ &amp;&amp; $y-&gt;{sign} =~ /^[+-]inf$/;
        return  1 if $x-&gt;{sign} =~ /^[+-]inf$/ &amp;&amp; $y-&gt;{sign} !~ /^[+-]inf$/;
        return -1;
    }

    my $t = $LIB-&gt;_mul($LIB-&gt;_copy($x-&gt;{_n}), $y-&gt;{_d});
    my $u = $LIB-&gt;_mul($LIB-&gt;_copy($y-&gt;{_n}), $x-&gt;{_d});
    $LIB-&gt;_acmp($t, $u);        # ignore signs
}

sub beq {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'beq() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for beq()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; ! $cmp;
}

sub bne {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bne() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bne()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; ! $cmp ? '' : 1;
}

sub blt {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'blt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for blt()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; $cmp &lt; 0;
}

sub ble {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'ble() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for ble()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; $cmp &lt;= 0;
}

sub bgt {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bgt() is an instance method, not a class method' unless $selfref;
    croak 'Wrong number of arguments for bgt()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; $cmp &gt; 0;
}

sub bge {
    my $self    = shift;
    my $selfref = ref $self;
    #my $class   = $selfref || $self;

    croak 'bge() is an instance method, not a class method'
        unless $selfref;
    croak 'Wrong number of arguments for bge()' unless @_ == 1;

    my $cmp = $self -&gt; bcmp(shift);
    return defined($cmp) &amp;&amp; $cmp &gt;= 0;
}

##############################################################################
# output conversion

sub numify {
    # convert 17/8 =&gt; float (aka 2.125)
    my ($self, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Non-finite number.

    if ($x -&gt; is_nan()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $inf - $inf;
    }

    if ($x -&gt; is_inf()) {
        require Math::Complex;
        my $inf = $Math::Complex::Inf;
        return $x -&gt; is_negative() ? -$inf : $inf;
    }

    # Finite number.

    my $abs = $LIB-&gt;_is_one($x-&gt;{_d})
            ? $LIB-&gt;_num($x-&gt;{_n})
            : Math::BigFloat -&gt; new($LIB-&gt;_str($x-&gt;{_n}))
                             -&gt; bdiv($LIB-&gt;_str($x-&gt;{_d}))
                             -&gt; bstr();
    return $x-&gt;{sign} eq '-' ? 0 - $abs : 0 + $abs;
}

sub as_int {
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    return $x -&gt; copy() if $x -&gt; isa("Math::BigInt");

    # Disable upgrading and downgrading.

    require Math::BigInt;
    my $upg = Math::BigInt -&gt; upgrade();
    my $dng = Math::BigInt -&gt; downgrade();
    Math::BigInt -&gt; upgrade(undef);
    Math::BigInt -&gt; downgrade(undef);

    # Copy the value.

    my $y;
    if ($x -&gt; is_inf()) {
        $y = Math::BigInt -&gt; binf($x-&gt;sign());
    } elsif ($x -&gt; is_nan()) {
        $y = Math::BigInt -&gt; bnan();
    } else {
        my $int = $LIB -&gt; _div($LIB -&gt; _copy($x-&gt;{_n}), $x-&gt;{_d});  # 22/7 =&gt; 3
        $y = Math::BigInt -&gt; new($LIB -&gt; _str($int));
        $y = $y -&gt; bneg() if $x -&gt; is_neg();
    }

    # Copy the remaining instance variables.

    ($y-&gt;{accuracy}, $y-&gt;{precision}) = ($x-&gt;{accuracy}, $x-&gt;{precision});

    # Restore upgrading and downgrading.

    Math::BigInt -&gt; upgrade($upg);
    Math::BigInt -&gt; downgrade($dng);

    return $y;
}

sub as_rat {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);
    carp "Rounding is not supported for ", (caller(0))[3], "()" if @r;

    return $x -&gt; copy() if $x -&gt; isa("Math::BigRat");

    # Disable upgrading and downgrading.

    my $upg = Math::BigRat -&gt; upgrade();
    my $dng = Math::BigRat -&gt; downgrade();
    Math::BigRat -&gt; upgrade(undef);
    Math::BigRat -&gt; downgrade(undef);

    # Copy the value.

    my $y = Math::BigRat -&gt; new($x);

    # Copy the remaining instance variables.

    ($y-&gt;{accuracy}, $y-&gt;{precision}) = ($x-&gt;{accuracy}, $x-&gt;{precision});

    # Restore upgrading and downgrading

    Math::BigRat -&gt; upgrade($upg);
    Math::BigRat -&gt; downgrade($dng);

    return $y;
}

sub as_float {
    my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_);

    return $x -&gt; copy() if $x -&gt; isa("Math::BigFloat");

    # Disable upgrading and downgrading.

    require Math::BigFloat;
    my $upg = Math::BigFloat -&gt; upgrade();
    my $dng = Math::BigFloat -&gt; downgrade();
    Math::BigFloat -&gt; upgrade(undef);
    Math::BigFloat -&gt; downgrade(undef);

    # Copy the value.

    my $y;
    if ($x -&gt; is_inf()) {
        $y = Math::BigFloat -&gt; binf($x-&gt;sign());
    } elsif ($x -&gt; is_nan()) {
        $y = Math::BigFloat -&gt; bnan();
    } else {
        $y = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_n}));
        $y -&gt; {sign} = $x -&gt; {sign};
        unless ($LIB -&gt; _is_one($x-&gt;{_d})) {
            my $xd = Math::BigFloat -&gt; new($LIB -&gt; _str($x-&gt;{_d}));
            $y -&gt; bdiv($xd, @r);
        }
    }

    # Copy the remaining instance variables.

    ($y-&gt;{accuracy}, $y-&gt;{precision}) = ($x-&gt;{accuracy}, $x-&gt;{precision});

    # Restore upgrading and downgrading.

    Math::BigFloat -&gt; upgrade($upg);
    Math::BigFloat -&gt; downgrade($dng);

    return $y;
}

sub to_hex {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    return $nan unless $x-&gt;is_int();

    my $str = $LIB-&gt;_to_hex($x-&gt;{_n});
    return $x-&gt;{sign} eq "-" ? "-$str" : $str;
}

sub to_oct {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    return $nan unless $x-&gt;is_int();

    my $str = $LIB-&gt;_to_oct($x-&gt;{_n});
    return $x-&gt;{sign} eq "-" ? "-$str" : $str;
}

sub to_bin {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    # Inf and NaN

    if ($x-&gt;{sign} ne '+' &amp;&amp; $x-&gt;{sign} ne '-') {
        return $x-&gt;{sign} unless $x-&gt;{sign} eq '+inf';  # -inf, NaN
        return 'inf';                                   # +inf
    }

    return $nan unless $x-&gt;is_int();

    my $str = $LIB-&gt;_to_bin($x-&gt;{_n});
    return $x-&gt;{sign} eq "-" ? "-$str" : $str;
}

sub as_bin {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x-&gt;is_int();

    my $s = $x-&gt;{sign};
    $s = '' if $s eq '+';
    $s . $LIB-&gt;_as_bin($x-&gt;{_n});
}

sub as_hex {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x-&gt;is_int();

    my $s = $x-&gt;{sign}; $s = '' if $s eq '+';
    $s . $LIB-&gt;_as_hex($x-&gt;{_n});
}

sub as_oct {
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);

    return $x unless $x-&gt;is_int();

    my $s = $x-&gt;{sign}; $s = '' if $s eq '+';
    $s . $LIB-&gt;_as_oct($x-&gt;{_n});
}

##############################################################################

# Create a Math::BigRat from a decimal string. This is an equivalent to
# from_hex(), from_oct(), and from_bin(). It is like new() except that it does
# not accept anything but a string representing a finite decimal number.

sub from_dec {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    # Make "require" work.

    $class -&gt; import() if $IMPORT == 0;

    # Don't modify constant (read-only) objects.

    return $self if $selfref &amp;&amp; $self-&gt;modify('from_dec');

    my $str = shift;
    my @r = @_;

    # If called as a class method, initialize a new object.

    $self = bless {}, $class unless $selfref;

    if (my @parts = $class -&gt; _dec_str_to_flt_lib_parts($str)) {
        my ($mant_sgn, $mant_abs, $expo_sgn, $expo_abs) = @parts;
        $self-&gt;{sign} = $mant_sgn;
        $self-&gt;{_n}   = $mant_abs;
        if ($expo_sgn eq "+") {
            $self-&gt;{_n} = $LIB -&gt; _lsft($self-&gt;{_n}, $expo_abs, 10);
            $self-&gt;{_d} = $LIB -&gt; _one();
        } else {
            $self-&gt;{_d} = $LIB -&gt; _1ex($mant_abs);
        }

        my $gcd = $LIB -&gt; _gcd($LIB -&gt; _copy($self-&gt;{_n}), $self-&gt;{_d});
        if (!$LIB -&gt; _is_one($gcd)) {
            $self -&gt; {_n} = $LIB -&gt; _div($self-&gt;{_n}, $gcd);
            $self -&gt; {_d} = $LIB -&gt; _div($self-&gt;{_d}, $gcd);
        }

        return $downgrade -&gt; new($self -&gt; bstr(), @r)
          if defined($downgrade) &amp;&amp; $self -&gt; is_int();
        return $self;
    }

    return $self -&gt; bnan(@r);
}

sub from_hex {
    my $class = shift;

    # The relationship should probably go the otherway, i.e, that new() calls
    # from_hex(). Fixme!
    my ($x, @r) = @_;
    $x =~ s|^\s*(?:0?[Xx]_*)?|0x|;
    $class-&gt;new($x, @r);
}

sub from_bin {
    my $class = shift;

    # The relationship should probably go the otherway, i.e, that new() calls
    # from_bin(). Fixme!
    my ($x, @r) = @_;
    $x =~ s|^\s*(?:0?[Bb]_*)?|0b|;
    $class-&gt;new($x, @r);
}

sub from_oct {
    my $class = shift;

    # Why is this different from from_hex() and from_bin()? Fixme!
    my @parts;
    for my $c (@_) {
        push @parts, Math::BigInt-&gt;from_oct($c);
    }
    $class-&gt;new (@parts);
}

##############################################################################
# import

sub import {
    my $class = shift;
    $IMPORT++;                  # remember we did import()
    my @a;                      # unrecognized arguments

    my @import = ();

    while (@_) {
        my $param = shift;

        # Enable overloading of constants.

        if ($param eq ':constant') {
            overload::constant

                integer =&gt; sub {
                    $class -&gt; new(shift);
                },

                float   =&gt; sub {
                    $class -&gt; new(shift);
                },

                binary  =&gt; sub {
                    # E.g., a literal 0377 shall result in an object whose value
                    # is decimal 255, but new("0377") returns decimal 377.
                    return $class -&gt; from_oct($_[0]) if $_[0] =~ /^0_*[0-7]/;
                    $class -&gt; new(shift);
                };
            next;
        }

        # Upgrading.

        if ($param eq 'upgrade') {
            $class -&gt; upgrade(shift);
            next;
        }

        # Downgrading.

        if ($param eq 'downgrade') {
            $class -&gt; downgrade(shift);
            next;
        }

        # Accuracy.

        if ($param eq 'accuracy') {
            $class -&gt; accuracy(shift);
            next;
        }

        # Precision.

        if ($param eq 'precision') {
            $class -&gt; precision(shift);
            next;
        }

        # Rounding mode.

        if ($param eq 'round_mode') {
            $class -&gt; round_mode(shift);
            next;
        }

        # Fall-back accuracy.

        if ($param eq 'div_scale') {
            $class -&gt; div_scale(shift);
            next;
        }

        # Backend library.

        if ($param =~ /^(lib|try|only)\z/) {
            push @import, $param;
            push @import, shift() if @_;
            next;
        }

        if ($param eq 'with') {
            # alternative class for our private parts()
            # XXX: no longer supported
            # $LIB = shift() || 'Calc';
            # carp "'with' is no longer supported, use 'lib', 'try', or 'only'";
            shift;
            next;
        }

        # Unrecognized parameter.

        push @a, $param;
    }

    Math::BigInt -&gt; import(@import);

    # find out which library was actually loaded
    $LIB = Math::BigInt -&gt; config("lib");

    $class -&gt; SUPER::import(@a);                        # for subclasses
    $class -&gt; export_to_level(1, $class, @a) if @a;     # need this, too
}

1;

__END__

=pod

=head1 NAME

Math::BigRat - arbitrary size rational number math package

=head1 SYNOPSIS

    use Math::BigRat;

    my $x = Math::BigRat-&gt;new('3/7'); $x += '5/9';

    print $x-&gt;bstr(), "\n";
    print $x ** 2, "\n";

    my $y = Math::BigRat-&gt;new('inf');
    print "$y ", ($y-&gt;is_inf ? 'is' : 'is not'), " infinity\n";

    my $z = Math::BigRat-&gt;new(144); $z-&gt;bsqrt();

=head1 DESCRIPTION

Math::BigRat complements Math::BigInt and Math::BigFloat by providing support
for arbitrary big rational numbers.

=head2 MATH LIBRARY

You can change the underlying module that does the low-level
math operations by using:

    use Math::BigRat try =&gt; 'GMP';

Note: This needs Math::BigInt::GMP installed.

The following would first try to find Math::BigInt::Foo, then
Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:

    use Math::BigRat try =&gt; 'Foo,Math::BigInt::Bar';

If you want to get warned when the fallback occurs, replace "try" with "lib":

    use Math::BigRat lib =&gt; 'Foo,Math::BigInt::Bar';

If you want the code to die instead, replace "try" with "only":

    use Math::BigRat only =&gt; 'Foo,Math::BigInt::Bar';

=head1 METHODS

Any methods not listed here are derived from Math::BigFloat (or
Math::BigInt), so make sure you check these two modules for further
information.

=over

=item new()

    $x = Math::BigRat-&gt;new('1/3');

Create a new Math::BigRat object. Input can come in various forms:

    $x = Math::BigRat-&gt;new(123);                            # scalars
    $x = Math::BigRat-&gt;new('inf');                          # infinity
    $x = Math::BigRat-&gt;new('123.3');                        # float
    $x = Math::BigRat-&gt;new('1/3');                          # simple string
    $x = Math::BigRat-&gt;new('1 / 3');                        # spaced
    $x = Math::BigRat-&gt;new('1 / 0.1');                      # w/ floats
    $x = Math::BigRat-&gt;new(Math::BigInt-&gt;new(3));           # BigInt
    $x = Math::BigRat-&gt;new(Math::BigFloat-&gt;new('3.1'));     # BigFloat
    $x = Math::BigRat-&gt;new(Math::BigInt::Lite-&gt;new('2'));   # BigLite

    # You can also give D and N as different objects:
    $x = Math::BigRat-&gt;new(
            Math::BigInt-&gt;new(-123),
            Math::BigInt-&gt;new(7),
         );                      # =&gt; -123/7

=item numerator()

    $n = $x-&gt;numerator();

Returns a copy of the numerator (the part above the line) as signed BigInt.

=item denominator()

    $d = $x-&gt;denominator();

Returns a copy of the denominator (the part under the line) as positive BigInt.

=item parts()

    ($n, $d) = $x-&gt;parts();

Return a list consisting of (signed) numerator and (unsigned) denominator as
BigInts.

=item dparts()

Returns the integer part and the fraction part.

=item fparts()

Returns the smallest possible numerator and denominator so that the numerator
divided by the denominator gives back the original value. For finite numbers,
both values are integers. Mnemonic: fraction.

=item numify()

    my $y = $x-&gt;numify();

Returns the object as a scalar. This will lose some data if the object
cannot be represented by a normal Perl scalar (integer or float), so
use L&lt;/as_int()&gt; or L&lt;/as_float()&gt; instead.

This routine is automatically used whenever a scalar is required:

    my $x = Math::BigRat-&gt;new('3/1');
    @array = (0, 1, 2, 3);
    $y = $array[$x];                # set $y to 3

=item as_int()

=item as_number()

    $x = Math::BigRat-&gt;new('13/7');
    print $x-&gt;as_int(), "\n";               # '1'

Returns a copy of the object as BigInt, truncated to an integer.

C&lt;as_number()&gt; is an alias for C&lt;as_int()&gt;.

=item as_float()

    $x = Math::BigRat-&gt;new('13/7');
    print $x-&gt;as_float(), "\n";             # '1'

    $x = Math::BigRat-&gt;new('2/3');
    print $x-&gt;as_float(5), "\n";            # '0.66667'

Returns a copy of the object as BigFloat, preserving the
accuracy as wanted, or the default of 40 digits.

This method was added in v0.22 of Math::BigRat (April 2008).

=item as_hex()

    $x = Math::BigRat-&gt;new('13');
    print $x-&gt;as_hex(), "\n";               # '0xd'

Returns the BigRat as hexadecimal string. Works only for integers.

=item as_bin()

    $x = Math::BigRat-&gt;new('13');
    print $x-&gt;as_bin(), "\n";               # '0x1101'

Returns the BigRat as binary string. Works only for integers.

=item as_oct()

    $x = Math::BigRat-&gt;new('13');
    print $x-&gt;as_oct(), "\n";               # '015'

Returns the BigRat as octal string. Works only for integers.

=item from_hex()

    my $h = Math::BigRat-&gt;from_hex('0x10');

Create a BigRat from a hexadecimal number in string form.

=item from_oct()

    my $o = Math::BigRat-&gt;from_oct('020');

Create a BigRat from an octal number in string form.

=item from_bin()

    my $b = Math::BigRat-&gt;from_bin('0b10000000');

Create a BigRat from an binary number in string form.

=item bnan()

    $x = Math::BigRat-&gt;bnan();

Creates a new BigRat object representing NaN (Not A Number).
If used on an object, it will set it to NaN:

    $x-&gt;bnan();

=item bzero()

    $x = Math::BigRat-&gt;bzero();

Creates a new BigRat object representing zero.
If used on an object, it will set it to zero:

    $x-&gt;bzero();

=item binf()

    $x = Math::BigRat-&gt;binf($sign);

Creates a new BigRat object representing infinity. The optional argument is
either '-' or '+', indicating whether you want infinity or minus infinity.
If used on an object, it will set it to infinity:

    $x-&gt;binf();
    $x-&gt;binf('-');

=item bone()

    $x = Math::BigRat-&gt;bone($sign);

Creates a new BigRat object representing one. The optional argument is
either '-' or '+', indicating whether you want one or minus one.
If used on an object, it will set it to one:

    $x-&gt;bone();                 # +1
    $x-&gt;bone('-');              # -1

=item length()

    $len = $x-&gt;length();

Return the length of $x in digits for integer values.

=item digit()

    print Math::BigRat-&gt;new('123/1')-&gt;digit(1);     # 1
    print Math::BigRat-&gt;new('123/1')-&gt;digit(-1);    # 3

Return the N'ths digit from X when X is an integer value.

=item bnorm()

    $x-&gt;bnorm();

Reduce the number to the shortest form. This routine is called
automatically whenever it is needed.

=item bfac()

    $x-&gt;bfac();

Calculates the factorial of $x. For instance:

    print Math::BigRat-&gt;new('3/1')-&gt;bfac(), "\n";   # 1*2*3
    print Math::BigRat-&gt;new('5/1')-&gt;bfac(), "\n";   # 1*2*3*4*5

Works currently only for integers.

=item bround()/round()/bfround()

Are not yet implemented.

=item bmod()

    $x-&gt;bmod($y);

Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the
result is identical to the remainder after floored division (F-division). If,
in addition, both $x and $y are integers, the result is identical to the result
from Perl's % operator.

=item bmodinv()

    $x-&gt;bmodinv($mod);          # modular multiplicative inverse

Returns the multiplicative inverse of C&lt;$x&gt; modulo C&lt;$mod&gt;. If

    $y = $x -&gt; copy() -&gt; bmodinv($mod)

then C&lt;$y&gt; is the number closest to zero, and with the same sign as C&lt;$mod&gt;,
satisfying

    ($x * $y) % $mod = 1 % $mod

If C&lt;$x&gt; and C&lt;$y&gt; are non-zero, they must be relative primes, i.e.,
C&lt;bgcd($y, $mod)==1&gt;. 'C&lt;NaN&gt;' is returned when no modular multiplicative
inverse exists.

=item bmodpow()

    $num-&gt;bmodpow($exp,$mod);           # modular exponentiation
                                        # ($num**$exp % $mod)

Returns the value of C&lt;$num&gt; taken to the power C&lt;$exp&gt; in the modulus
C&lt;$mod&gt; using binary exponentiation.  C&lt;bmodpow&gt; is far superior to
writing

    $num ** $exp % $mod

because it is much faster - it reduces internal variables into
the modulus whenever possible, so it operates on smaller numbers.

C&lt;bmodpow&gt; also supports negative exponents.

    bmodpow($num, -1, $mod)

is exactly equivalent to

    bmodinv($num, $mod)

=item bneg()

    $x-&gt;bneg();

Used to negate the object in-place.

=item is_one()

    print "$x is 1\n" if $x-&gt;is_one();

Return true if $x is exactly one, otherwise false.

=item is_zero()

    print "$x is 0\n" if $x-&gt;is_zero();

Return true if $x is exactly zero, otherwise false.

=item is_pos()/is_positive()

    print "$x is &gt;= 0\n" if $x-&gt;is_positive();

Return true if $x is positive (greater than or equal to zero), otherwise
false. Please note that '+inf' is also positive, while 'NaN' and '-inf' aren't.

C&lt;is_positive()&gt; is an alias for C&lt;is_pos()&gt;.

=item is_neg()/is_negative()

    print "$x is &lt; 0\n" if $x-&gt;is_negative();

Return true if $x is negative (smaller than zero), otherwise false. Please
note that '-inf' is also negative, while 'NaN' and '+inf' aren't.

C&lt;is_negative()&gt; is an alias for C&lt;is_neg()&gt;.

=item is_int()

    print "$x is an integer\n" if $x-&gt;is_int();

Return true if $x has a denominator of 1 (e.g. no fraction parts), otherwise
false. Please note that '-inf', 'inf' and 'NaN' aren't integer.

=item is_odd()

    print "$x is odd\n" if $x-&gt;is_odd();

Return true if $x is odd, otherwise false.

=item is_even()

    print "$x is even\n" if $x-&gt;is_even();

Return true if $x is even, otherwise false.

=item bceil()

    $x-&gt;bceil();

Set $x to the next bigger integer value (e.g. truncate the number to integer
and then increment it by one).

=item bfloor()

    $x-&gt;bfloor();

Truncate $x to an integer value.

=item bint()

    $x-&gt;bint();

Round $x towards zero.

=item bsqrt()

    $x-&gt;bsqrt();

Calculate the square root of $x.

=item broot()

    $x-&gt;broot($n);

Calculate the N'th root of $x.

=item badd()

    $x-&gt;badd($y);

Adds $y to $x and returns the result.

=item bmul()

    $x-&gt;bmul($y);

Multiplies $y to $x and returns the result.

=item bsub()

    $x-&gt;bsub($y);

Subtracts $y from $x and returns the result.

=item bdiv()

    $q = $x-&gt;bdiv($y);
    ($q, $r) = $x-&gt;bdiv($y);

In scalar context, divides $x by $y and returns the result. In list context,
does floored division (F-division), returning an integer $q and a remainder $r
so that $x = $q * $y + $r. The remainer (modulo) is equal to what is returned
by C&lt;&lt; $x-&gt;bmod($y) &gt;&gt;.

=item binv()

    $x-&gt;binv();

Inverse of $x.

=item bdec()

    $x-&gt;bdec();

Decrements $x by 1 and returns the result.

=item binc()

    $x-&gt;binc();

Increments $x by 1 and returns the result.

=item copy()

    my $z = $x-&gt;copy();

Makes a deep copy of the object.

Please see the documentation in L&lt;Math::BigInt&gt; for further details.

=item bstr()/bsstr()

    my $x = Math::BigRat-&gt;new('8/4');
    print $x-&gt;bstr(), "\n";             # prints 1/2
    print $x-&gt;bsstr(), "\n";            # prints 1/2

Return a string representing this object.

=item bcmp()

    $x-&gt;bcmp($y);

Compares $x with $y and takes the sign into account.
Returns -1, 0, 1 or undef.

=item bacmp()

    $x-&gt;bacmp($y);

Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or undef.

=item beq()

    $x -&gt; beq($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item bne()

    $x -&gt; bne($y);

Returns true if and only if $x is not equal to $y, and false otherwise.

=item blt()

    $x -&gt; blt($y);

Returns true if and only if $x is equal to $y, and false otherwise.

=item ble()

    $x -&gt; ble($y);

Returns true if and only if $x is less than or equal to $y, and false
otherwise.

=item bgt()

    $x -&gt; bgt($y);

Returns true if and only if $x is greater than $y, and false otherwise.

=item bge()

    $x -&gt; bge($y);

Returns true if and only if $x is greater than or equal to $y, and false
otherwise.

=item blsft()/brsft()

Used to shift numbers left/right.

Please see the documentation in L&lt;Math::BigInt&gt; for further details.

=item band()

    $x-&gt;band($y);               # bitwise and

=item bior()

    $x-&gt;bior($y);               # bitwise inclusive or

=item bxor()

    $x-&gt;bxor($y);               # bitwise exclusive or

=item bnot()

    $x-&gt;bnot();                 # bitwise not (two's complement)

=item bpow()

    $x-&gt;bpow($y);

Compute $x ** $y.

Please see the documentation in L&lt;Math::BigInt&gt; for further details.

=item blog()

    $x-&gt;blog($base, $accuracy);         # logarithm of x to the base $base

If C&lt;$base&gt; is not defined, Euler's number (e) is used:

    print $x-&gt;blog(undef, 100);         # log(x) to 100 digits

=item bexp()

    $x-&gt;bexp($accuracy);        # calculate e ** X

Calculates two integers A and B so that A/B is equal to C&lt;e ** $x&gt;, where C&lt;e&gt; is
Euler's number.

This method was added in v0.20 of Math::BigRat (May 2007).

See also C&lt;blog()&gt;.

=item bnok()

    $x-&gt;bnok($y);               # x over y (binomial coefficient n over k)

Calculates the binomial coefficient n over k, also called the "choose"
function. The result is equivalent to:

    ( n )      n!
    | - |  = -------
    ( k )    k!(n-k)!

This method was added in v0.20 of Math::BigRat (May 2007).

=item config()

    Math::BigRat-&gt;config("trap_nan" =&gt; 1);      # set
    $accu = Math::BigRat-&gt;config("accuracy");   # get

Set or get configuration parameter values. Read-only parameters are marked as
RO. Read-write parameters are marked as RW. The following parameters are
supported.

    Parameter       RO/RW   Description
                            Example
    ============================================================
    lib             RO      Name of the math backend library
                            Math::BigInt::Calc
    lib_version     RO      Version of the math backend library
                            0.30
    class           RO      The class of config you just called
                            Math::BigRat
    version         RO      version number of the class you used
                            0.10
    upgrade         RW      To which class numbers are upgraded
                            undef
    downgrade       RW      To which class numbers are downgraded
                            undef
    precision       RW      Global precision
                            undef
    accuracy        RW      Global accuracy
                            undef
    round_mode      RW      Global round mode
                            even
    div_scale       RW      Fallback accuracy for div, sqrt etc.
                            40
    trap_nan        RW      Trap NaNs
                            undef
    trap_inf        RW      Trap +inf/-inf
                            undef

=back

=head1 NUMERIC LITERALS

After C&lt;use Math::BigRat ':constant'&gt; all numeric literals in the given scope
are converted to C&lt;Math::BigRat&gt; objects. This conversion happens at compile
time. Every non-integer is convert to a NaN.

For example,

    perl -MMath::BigRat=:constant -le 'print 2**150'

prints the exact value of C&lt;2**150&gt;. Note that without conversion of constants
to objects the expression C&lt;2**150&gt; is calculated using Perl scalars, which
leads to an inaccurate result.

Please note that strings are not affected, so that

    use Math::BigRat qw/:constant/;

    $x = "1234567890123456789012345678901234567890"
            + "123456789123456789";

does give you what you expect. You need an explicit Math::BigRat-&gt;new() around
at least one of the operands. You should also quote large constants to prevent
loss of precision:

    use Math::BigRat;

    $x = Math::BigRat-&gt;new("1234567889123456789123456789123456789");

Without the quotes Perl first converts the large number to a floating point
constant at compile time, and then converts the result to a Math::BigRat object
at run time, which results in an inaccurate result.

=head2 Hexadecimal, octal, and binary floating point literals

Perl (and this module) accepts hexadecimal, octal, and binary floating point
literals, but use them with care with Perl versions before v5.32.0, because some
versions of Perl silently give the wrong result. Below are some examples of
different ways to write the number decimal 314.

Hexadecimal floating point literals:

    0x1.3ap+8         0X1.3AP+8
    0x1.3ap8          0X1.3AP8
    0x13a0p-4         0X13A0P-4

Octal floating point literals (with "0" prefix):

    01.164p+8         01.164P+8
    01.164p8          01.164P8
    011640p-4         011640P-4

Octal floating point literals (with "0o" prefix) (requires v5.34.0):

    0o1.164p+8        0O1.164P+8
    0o1.164p8         0O1.164P8
    0o11640p-4        0O11640P-4

Binary floating point literals:

    0b1.0011101p+8    0B1.0011101P+8
    0b1.0011101p8     0B1.0011101P8
    0b10011101000p-2  0B10011101000P-2

=head1 BUGS

Please report any bugs or feature requests to
C&lt;bug-math-bigint at rt.cpan.org&gt;, or through the web interface at
L&lt;https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt&gt; (requires login).
We will be notified, and then you'll automatically be notified of progress on
your bug as I make changes.

=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc Math::BigInt

You can also look for information at:

=over 4

=item * GitHub

L&lt;https://github.com/pjacklam/p5-Math-BigInt&gt;

=item * RT: CPAN's request tracker

L&lt;https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt&gt;

=item * MetaCPAN

L&lt;https://metacpan.org/release/Math-BigInt&gt;

=item * CPAN Testers Matrix

L&lt;http://matrix.cpantesters.org/?dist=Math-BigInt&gt;

=back

=head1 LICENSE

This program is free software; you may redistribute it and/or modify it under
the same terms as Perl itself.

=head1 SEE ALSO

L&lt;Math::BigInt&gt; and L&lt;Math::BigFloat&gt; as well as the backend libraries
L&lt;Math::BigInt::FastCalc&gt;, L&lt;Math::BigInt::GMP&gt;, and L&lt;Math::BigInt::Pari&gt;,
L&lt;Math::BigInt::GMPz&gt;, and L&lt;Math::BigInt::BitVect&gt;.

The pragmas L&lt;bigint&gt;, L&lt;bigfloat&gt;, and L&lt;bigrat&gt; might also be of interest. In
addition there is the L&lt;bignum&gt; pragma which does upgrading and downgrading.

=head1 AUTHORS

=over 4

=item *

Tels L&lt;http://bloodgate.com/&gt; 2001-2009.

=item *

Maintained by Peter John Acklam &lt;pjacklam@gmail.com&gt; 2011-

=back

=cut
</pre></body></html>