65.9K
CodeProject is changing. Read more.
Home

.NET Rational (fraction) value type using Decimals, written in C#

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.28/5 (6 votes)

Jan 24, 2006

CPOL
viewsIcon

37663

downloadIcon

235

Implements a Rational datatype.

Introduction

The class presented in this article implements a rational value type with basic mathematical functionality.

Using the code

This class has no public constructors.

Implicit casting to/from Int64 (and therefore other integer types) and decimal (and therefore float and double) is supported.

// Cast from int
PIEBALD.Types.Rational a = 1 ;
// Cast from double (via decimal)
PIEBALD.Types.Rational b = 2.3 ;
// Cast from decimal
PIEBALD.Types.Rational c = 4.5M ;

Conversion from decimal can be controlled by the ConversionMethod static property. Currently, the DecimalConversionMethod enumeration defines two values: Decimal and BestGuess. Decimal simply uses a power of ten as the denominator. BestGuess tries (with some success) to determine what numbers can be divided to produce the value.

// This is the default
PIEBALD.Types.Rational.ConversionMethod = 
               DecimalConversionMethod.Decimal;
// Yields 33333333333333333333
//    33333333/10000000000000000000000000000
PIEBALD.Types.Rational d = 1M / 3M ;
PIEBALD.Types.Rational.ConversionMethod = 
             DecimalConversionMethod.BestGuess;
// Yields 1/3
PIEBALD.Types.Rational e = 1M / 3M ;

Strings containing expressions can be assigned with the ParseInfix and ParseRpn methods.

// Convert from string
PIEBALD.Types.Rational f = 
   PIEBALD.Types.Rational.ParseInfix ( "1/2" ) ;
// Convert from string
PIEBALD.Types.Rational g = 
   PIEBALD.Types.Rational.ParseInfix ( "(1/2) / (3/4)" ) ;
// Convert from string
PIEBALD.Types.Rational h = 
   PIEBALD.Types.Rational.ParseRpn ( "1 2 /" ) ;

See my PIEBALD.Lib.LibRpn class for information on how infix is transformed to RPN.

The mathematical operators (+, -, *, /, %, ^ (exponentiation)) are supported. There are other static and instance properties as well.

History

  • First posted - 2006/01/16.
OSZAR »