#
# "Tax the rat farms." - Lord Vetinari
#
# The following hash values are used:
# sign : +,-,NaN,+inf,-inf
# _d : denominator
# _n : numeraotr (value = _n/_d)
# _a : accuracy
# _p : precision
# _f : flags, used by MBR to flag parts of a rational as untouchable
# You should not look at the innards of a BigRat - use the methods for this.
require 5.005_03;
use strict;
require Exporter;
$VERSION = '0.12';
use overload; # inherit from Math::BigFloat
##############################################################################
# global constants, flags and accessory
$round_mode = 'even';
$div_scale = 40;
$upgrade = undef;
$downgrade = undef;
# these are internally, and not to be used from the outside
my $nan = 'NaN';
my $MBI = 'Math::BigInt';
my $CALC = 'Math::BigInt::Calc';
my $class = 'Math::BigRat';
my $IMPORT = 0;
sub isa
{
}
sub BEGIN
{
}
sub _new_from_float
{
# turn a single float input into a rational number (like '0.1')
my ($self,$f) = @_;
if ($f->{_es} eq '-')
{
# something like Math::BigRat->new('0.1');
# 1 / 1 => 1/10
}
else
{
# something like Math::BigRat->new('10');
# 1 / 1 => 10/1
}
$self;
}
sub new
{
# create a Math::BigRat
my $class = shift;
my ($n,$d) = shift;
# input like (BigInt,BigInt) or (BigFloat,BigFloat) not handled yet
if ((!defined $d) && (ref $n) && (!$n->isa('Math::BigRat')))
{
if ($n->isa('Math::BigFloat'))
{
$self->_new_from_float($n);
}
if ($n->isa('Math::BigInt'))
{
# TODO: trap NaN, inf
}
if ($n->isa('Math::BigInt::Lite'))
{
# TODO: trap NaN, inf
}
}
return $n->copy() if ref $n;
if (!defined $n)
{
}
# string input with / delimiter
if ($n =~ /\s*\/\s*/)
{
($n,$d) = split (/\//,$n);
# try as BigFloats first
{
# one of them looks like a float
# Math::BigFloat($n,undef,undef) does not what it is supposed to do, so:
# now correct $self->{_n} due to $n
# calculate the difference between nE and dE
if ($diff_e->is_negative())
{
# < 0: mul d with it
}
{
# > 0: mul n with it
}
}
else
{
# both d and n are (big)ints
# handle inf and NAN cases:
{
{
my $s = '+'; # '+inf/+123' or '-inf/-123'
# +-inf/123 => +-inf
}
# 123/inf => 0
}
# if $d is negative, flip sign
}
}
# simple string input
if (($n =~ /[\.eE]/))
{
# looks like a float, quacks like a float, so probably is a float
# Math::BigFloat($n,undef,undef) does not what it is supposed to do, so:
}
else
{
}
}
sub copy
{
my ($c,$x);
if (@_ > 1)
{
# if two arguments, the first one is the class to "swallow" subclasses
($c,$x) = @_;
}
else
{
$x = shift;
$c = ref($x);
}
return unless ref($x); # only for objects
$self;
}
##############################################################################
sub config
{
# return (later set?) configuration data as hash ref
my $class = shift || 'Math::BigFloat';
# now we need only to override the ones that are different from our parent
$cfg;
}
##############################################################################
sub bstr
{
if ($x->{sign} !~ /^[+-]$/) # inf, NaN etc
{
my $s = $x->{sign}; $s =~ s/^\+//; # +inf => inf
return $s;
}
}
sub bsstr
{
if ($x->{sign} !~ /^[+-]$/) # inf, NaN etc
{
my $s = $x->{sign}; $s =~ s/^\+//; # +inf => inf
return $s;
}
}
sub bnorm
{
# reduce the number to the shortest form and remember this (so that we
# don't reduce again)
# both parts must be BigInt's (or whatever we are using today)
{
}
{
}
# this is to prevent automatically rounding when MBI's globals are set
# 'forget' that parts were rounded via MBI::bround() in MBF's bfround()
# no normalize for NaN, inf etc.
return $x if $x->{sign} !~ /^[+-]$/;
# normalize zeros to 0/1
if (($x->{sign} =~ /^[+-]$/) &&
{
return $x;
}
# reduce other numbers
# disable upgrade in BigInt, otherwise deep recursion
{
}
$x;
}
##############################################################################
# special values
sub _bnan
{
# used by parent class bnan() to initialize number to NaN
my $self = shift;
if ($_trap_nan)
{
require Carp;
Carp::croak ("Tried to set $self to NaN in $class\::_bnan()");
}
}
sub _binf
{
# used by parent class bone() to initialize number to +inf/-inf
my $self = shift;
if ($_trap_inf)
{
require Carp;
Carp::croak ("Tried to set $self to inf in $class\::_binf()");
}
}
sub _bone
{
# used by parent class bone() to initialize number to +1/-1
my $self = shift;
}
sub _bzero
{
# used by parent class bzero() to initialize number to 0
my $self = shift;
}
##############################################################################
sub badd
{
# add two rational numbers
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# TODO: inf handling
# 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 41
# - + - = --------- = --
# 4 3 4*3 12
# the gcd() calculation and reducing is then done in bnorm()
# calculate sign of result and norm our _n part
}
sub bsub
{
# subtract two rational numbers
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# flip sign of $x, call badd(), then flip sign of result
$x->{sign} =~ tr/+-/-+/
$x->badd($y,@r); # does norm and round
$x->{sign} =~ tr/+-/-+/
$x;
}
sub bmul
{
# multiply two rational numbers
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# inf handling
{
# result will always be +-inf:
# +inf * +/+inf => +inf, -inf * -/-inf => +inf
# +inf * -/-inf => -inf, -inf * +/+inf => -inf
return $x->binf('-');
}
# x== 0 # also: or y == 1 or y == -1
# According to Knuth, this can be optimized by doingtwice gcd (for d and n)
# and reducing in one step)
# 1 1 2 1
# - * - = - = -
# 4 3 12 6
# compute new sign
}
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 ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# x== 0 # also: or y == 1 or y == -1
# TODO: list context, upgrade
# 1 1 1 3
# - / - == - * -
# 4 3 4 1
# compute new sign
$x;
}
sub bmod
{
# compute "remainder" (in Perl way) of $x / $y
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
return $x if $x->is_zero(); # 0 / 7 = 0, mod 0
# compute $x - $y * floor($x/$y), keeping the sign of $x
# locally disable these, since they would interfere
# first, do a "normal" division ($x/$y)
# compute floor
{
# no need to set $u->{_d} to 1, since later we set it to $y->{_d}
#$x->{_n}->binc() if $x->{sign} eq '-'; # -22/7 => -4/1
}
# compute $y * $u
# compute $x - $u
$x->bsub($u);
}
##############################################################################
sub bdec
{
# decrement value (subtract 1)
return $x if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf
if ($x->{sign} eq '-')
{
}
else
{
{
# 1/3 -- => -2/3
$x->{sign} = '-';
}
else
{
}
}
}
sub binc
{
# increment value (add 1)
return $x if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf
if ($x->{sign} eq '-')
{
{
# -1/3 ++ => 2/3 (overflow at 0)
$x->{sign} = '+';
}
else
{
}
}
else
{
}
}
##############################################################################
# is_foo methods (the rest is inherited)
sub is_int
{
# return true if arg (BRAT or num_str) is an integer
0;
}
sub is_zero
{
# return true if arg (BRAT or num_str) is zero
0;
}
sub is_one
{
# return true if arg (BRAT or num_str) is +1 or -1 if signis given
return 1
0;
}
sub is_odd
{
# return true if arg (BFLOAT or num_str) is odd or false if even
0;
}
sub is_even
{
# return true if arg (BINT or num_str) is even or false if odd
0;
}
##############################################################################
# parts() and friends
sub numerator
{
$n;
}
sub denominator
{
}
sub parts
{
}
sub length
{
$x->{_n}->length(); # length(-123/1) => length(123)
}
sub digit
{
}
##############################################################################
# special calc routines
sub bceil
{
return $x unless $x->{sign} =~ /^[+-]$/;
$x;
}
sub bfloor
{
return $x unless $x->{sign} =~ /^[+-]$/;
$x;
}
sub bfac
{
# if $x is an integer
{
return $x->round(@r);
}
$x->bnan();
}
sub bpow
{
# power ($x ** $y)
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
{
# my Casio FX-5500L has a bug here: -1 ** 2 is -1, but -1 * -1 is 1;
}
# 1 ** -y => 1 / (1 ** |y|)
# so do test for negative $y after above's clause
# return $x->bnan() if $y->{sign} eq '-';
{
# shortcut for x/1 and y/1
{
if ($y->{sign} eq '-')
{
# 0.2 ** -3 => 1/(0.2 ** 3)
}
# correct sign; + ** + => +
if ($x->{sign} eq '-')
{
# - * - => +, - * - * - => -
}
return $x->round(@r);
}
# x/z ** y/1
if ($y->{sign} eq '-')
{
# 0.2 ** -3 => 1/(0.2 ** 3)
}
# correct sign; + ** + => +
if ($x->{sign} eq '-')
{
# - * - => +, - * - * - => -
}
return $x->round(@r);
}
# regular calculation (this is wrong for d/e ** f/g)
{
$x->bmul($x);
}
# n ** -x => 1/n ** x
}
sub blog
{
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# blog(1,Y) => 0
# $x <= 0 => NaN
{
}
# do it with floats
}
sub _as_float
{
my $x = shift;
# 22/7 => 3.142857143..
}
sub broot
{
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
{
}
# do it with floats
}
sub bmodpow
{
# set up parameters
my ($self,$x,$y,$m,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# $x or $y or $m are NaN or +-inf => NaN
return $x->bnan()
$m->{sign} !~ /^[+-]$/;
{
}
warn ("bmodpow() not fully implemented");
$x->bnan();
}
sub bmodinv
{
# set up parameters
my ($self,$x,$y,@r) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
# $x or $y are NaN or +-inf => NaN
return $x->bnan()
{
}
warn ("bmodinv() not fully implemented");
$x->bnan();
}
sub bsqrt
{
# if sqrt(D) was not integer
{
}
# if sqrt(N) was not integer
{
}
# convert parts to $MBI again
}
sub blsft
{
$b = 2 unless defined $b;
$b = $self->new($b) unless ref ($b);
$x;
}
sub brsft
{
$b = 2 unless defined $b;
$b = $self->new($b) unless ref ($b);
$x;
}
##############################################################################
# round
sub round
{
$_[0];
}
sub bround
{
$_[0];
}
sub bfround
{
$_[0];
}
##############################################################################
# comparing
sub bcmp
{
# compare two signed numbers
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
{
# handle +-inf and NaN
return +1;
}
# check sign for speed first
# shortcut
$t->bcmp($u);
}
sub bacmp
{
# compare two numbers (as unsigned)
# set up parameters
my ($self,$x,$y) = (ref($_[0]),@_);
# objectify is costly, so avoid it
if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1])))
{
}
{
# handle +-inf and NaN
return -1;
}
$t->bacmp($u);
}
##############################################################################
# output conversation
sub numify
{
# convert 17/8 => float (aka 2.125)
# N/1 => N
# N/D
}
sub as_number
{
return $x if $x->{sign} !~ /^[+-]$/; # NaN, inf etc
# need to disable these, otherwise bdiv() gives BigRat again
$t;
}
sub as_bin
{
return $x unless $x->is_int();
}
sub as_hex
{
return $x unless $x->is_int();
}
sub import
{
my $self = shift;
my $l = scalar @_;
my $lib = ''; my @a;
$IMPORT++;
for ( my $i = 0; $i < $l ; $i++)
{
# print "at $_[$i] (",$_[$i+1]||'undef',")\n";
if ( $_[$i] eq ':constant' )
{
# this rest causes overlord er load to step in
# print "overload @_\n";
}
# elsif ($_[$i] eq 'upgrade')
# {
# # this causes upgrading
# $upgrade = $_[$i+1]; # or undef to disable
# $i++;
# }
elsif ($_[$i] eq 'downgrade')
{
# this causes downgrading
$i++;
}
elsif ($_[$i] eq 'lib')
{
$i++;
}
elsif ($_[$i] eq 'with')
{
$i++;
}
else
{
push @a, $_[$i];
}
}
# let use Math::BigInt lib => 'GMP'; use Math::BigRat; still work
{
# MBI already loaded
}
else
{
# MBI not loaded, or not with "Math::BigInt"
if ($] < 5.006)
{
# Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is
# used in the same script, or eval inside import().
}
else
{
my $rc = "use $MBI lib => '$lib', 'objectify';";
eval $rc;
}
}
if ($@)
{
}
# any non :constant stuff is handled by our parent, Exporter
# even if @_ is empty, to give it a chance
}
1;
=head1 NAME
Math::BigRat - arbitrarily big rational numbers
=head1 SYNOPSIS
use Math::BigRat;
my $x = Math::BigRat->new('3/7'); $x += '5/9';
print $x->bstr(),"\n";
print $x ** 2,"\n";
my $y = Math::BigRat->new('inf');
print "$y ", ($y->is_inf ? 'is' : 'is not') , " infinity\n";
my $z = Math::BigRat->new(144); $z->bsqrt();
=head1 DESCRIPTION
Math::BigRat complements Math::BigInt and Math::BigFloat by providing support
for arbitrarily big rational numbers.
=head2 MATH LIBRARY
Math with the numbers is done (by default) by a module called
Math::BigInt::Calc. This is equivalent to saying:
use Math::BigRat lib => 'Calc';
You can change this by using:
use Math::BigRat lib => 'BitVect';
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 lib => 'Foo,Math::BigInt::Bar';
Calc.pm uses as internal format an array of elements of some decimal base
(usually 1e7, but this might be different for some systems) with the least
significant digit first, while BitVect.pm uses a bit vector of base 2, most
significant bit first. Other modules might use even different means of
representing the numbers. See the respective module documentation for further
details.
Currently the following replacement libraries exist, search for them at CPAN:
Math::BigInt::BitVect
Math::BigInt::GMP
Math::BigInt::Pari
Math::BigInt::FastCalc
=head1 METHODS
Any methods not listed here are dervied from Math::BigFloat (or
Math::BigInt), so make sure you check these two modules for further
information.
=head2 new()
$x = Math::BigRat->new('1/3');
Create a new Math::BigRat object. Input can come in various forms:
$x = Math::BigRat->new(123); # scalars
$x = Math::BigRat->new('inf'); # infinity
$x = Math::BigRat->new('123.3'); # float
$x = Math::BigRat->new('1/3'); # simple string
$x = Math::BigRat->new('1 / 3'); # spaced
$x = Math::BigRat->new('1 / 0.1'); # w/ floats
$x = Math::BigRat->new(Math::BigInt->new(3)); # BigInt
$x = Math::BigRat->new(Math::BigFloat->new('3.1')); # BigFloat
$x = Math::BigRat->new(Math::BigInt::Lite->new('2')); # BigLite
=head2 numerator()
$n = $x->numerator();
Returns a copy of the numerator (the part above the line) as signed BigInt.
=head2 denominator()
$d = $x->denominator();
Returns a copy of the denominator (the part under the line) as positive BigInt.
=head2 parts()
($n,$d) = $x->parts();
Return a list consisting of (signed) numerator and (unsigned) denominator as
BigInts.
=head2 as_number()
$x = Math::BigRat->new('13/7');
print $x->as_number(),"\n"; # '1'
Returns a copy of the object as BigInt trunced it to integer.
=head2 bfac()
$x->bfac();
Calculates the factorial of $x. For instance:
print Math::BigRat->new('3/1')->bfac(),"\n"; # 1*2*3
print Math::BigRat->new('5/1')->bfac(),"\n"; # 1*2*3*4*5
Works currently only for integers.
=head2 blog()
Is not yet implemented.
=head2 bround()/round()/bfround()
Are not yet implemented.
=head2 bmod()
use Math::BigRat;
my $x = Math::BigRat->new('7/4');
my $y = Math::BigRat->new('4/3');
print $x->bmod($y);
Set $x to the remainder of the division of $x by $y.
=head2 is_one()
print "$x is 1\n" if $x->is_one();
Return true if $x is exactly one, otherwise false.
=head2 is_zero()
print "$x is 0\n" if $x->is_zero();
Return true if $x is exactly zero, otherwise false.
=head2 is_positive()
print "$x is >= 0\n" if $x->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.
=head2 is_negative()
print "$x is < 0\n" if $x->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.
=head2 is_int()
print "$x is an integer\n" if $x->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.
=head2 is_odd()
print "$x is odd\n" if $x->is_odd();
Return true if $x is odd, otherwise false.
=head2 is_even()
print "$x is even\n" if $x->is_even();
Return true if $x is even, otherwise false.
=head2 bceil()
$x->bceil();
Set $x to the next bigger integer value (e.g. truncate the number to integer
and then increment it by one).
=head2 bfloor()
$x->bfloor();
Truncate $x to an integer value.
=head2 bsqrt()
$x->bsqrt();
Calculate the square root of $x.
=head2 config
use Data::Dumper;
print Dumper ( Math::BigRat->config() );
print Math::BigRat->config()->{lib},"\n";
Returns a hash containing the configuration, e.g. the version number, lib
loaded etc. The following hash keys are currently filled in with the
appropriate information.
Example
============================================================
lib RO Name of the Math library
Math::BigInt::Calc
lib_version RO Version of 'lib'
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 acccuracy for div
40
trap_nan RW Trap creation of NaN (undef = no)
undef
trap_inf RW Trap creation of +inf/-inf (undef = no)
undef
By passing a reference to a hash you may set the configuration values. This
works only for values that a marked with a C<RW> above, anything else is
read-only.
=head1 BUGS
Some things are not yet implemented, or only implemented half-way:
=over 2
=item inf handling (partial)
=item NaN handling (partial)
=item $x ** $y where $y is not an integer
=item bmod(), blog(), bmodinv() and bmodpow() (partial)
=back
=head1 LICENSE
the same terms as Perl itself.
=head1 SEE ALSO
L<Math::BigFloat> and L<Math::Big> as well as L<Math::BigInt::BitVect>,
L<Math::BigInt::Pari> and L<Math::BigInt::GMP>.
See L<http://search.cpan.org/search?dist=bignum> for a way to use
Math::BigRat.
The package at L<http://search.cpan.org/search?dist=Math%3A%3ABigRat>
may contain more documentation and examples as well as testcases.
=head1 AUTHORS
(C) by Tels L<http://bloodgate.com/> 2001, 2002, 2003, 2004.
=cut