Algorithmic Solutions > LEDA > LEDA Guide > Number Types > Rational Numbers

Rational Numbers

The data type rational represents a rational number, i.e., the quotient of two integer numbers. A rational is implemented by two Integers of Arbitrary Length, representing the numerator and denominator.

Remark: Rational Numbers are not necessarily normalized, that is, numerator and denominator may have common factors. Call normalize() once in a while.

Example

The following program shows how rational can be used in a program.

#include <LEDA/numbers/rational.h>
#include <LEDA/numbers/integer.h>

using namespace leda;

int main() {
  integer denominator=1;
  int i; 
  for (i=1;i<=40;i++) {denominator*=i;} //generate denominator that does
                                        //not fit into a double :-)

  rational r(1000,denominator);         //create a rational r   
  std::cout << "r=" << r << std::endl;

  //operations on and with r
  r.normalize();                                     
  std::cout << "After r.normalize(): r=" << r << std::endl;

  rational s=3.0*r+r.inverse();
  std::cout << "\ns=" << s << std::endl;
 
  r.invert();
  std::cout << "\nAfter r.invert(): r=" << r << std::endl;

  std::cout << "\nsqr(r)="  << sqr(r)  << std::endl;
  std::cout << "\nceil(r)=" << ceil(r) << std::endl;

  return 0;
}	    

Strengths

  • computations with rationals always yield mathematically correct results
  • can be used like double and together with built-in number types
  • many arithmetic operations predefined
  • efficient implementation (in general, more efficient than Algebraic Real Numbers)
  • space efficient (no intermediate results are stored)

Disadvantages

  • about 30-100 times slower than double

Tips

Use rationals if you need exact arithmetic for rational numbers.

See also:

Integers of Arbitrary Length

Algebraic Real Numbers

Big Floatingpoint Numbers

Floating Point Filter

Interval Arithmetic


Vectors and Matrices with Integer Entries

Vectors and Matrices with Double Entries

Rational Vectors

Functions of numerical analysis


Manual Entries:

Manual Page Rational Numbers




Please send any suggestions, comments or questions to leda@algorithmic-solutions.com
© Copyright 2001-2003, Algorithmic Solutions Software GmbH