9

Is there any standard C# type or library for exact rational arithmetic, like division?

Decimal isn't what I need:

1m/3m + 1m/3m + 1m/3m != 1

I am thinking about something which stores two decimals, numerator and denominator, and performs multiplications and divisions exactly. Which can simplify fractions when needed and do explicit conversion to double or decimal.

dav_i
  • 27,509
  • 17
  • 104
  • 136
user2622016
  • 6,060
  • 3
  • 32
  • 53
  • 1
    Check [this](http://www.codeproject.com/Articles/11971/Fractions-in-C) out, it might help you implement it yourself at least. – Tobberoth Nov 08 '13 at 09:33
  • I implemented this once using System.Numerics.BigInteger and it wasn't a big deal. Problem is that such an approach can be very very slow since every multiplication or division duplicates the number of digits in the nominator or denominator. – helb Nov 08 '13 at 09:35
  • There is such a type in Microsoft.SolverFoundation.Common, but I prefer not to rely on it (no one has that DLL). It's easy to roll your own anyway. – harold Nov 08 '13 at 09:39
  • 1
    Besides the link commented by @Tobberoth, you can also check [this one](http://www.codeproject.com/Articles/88980/Rational-Numbers-NET-4-0-Version-Rational-Computin). – J.A.I.L. Nov 08 '13 at 09:40
  • simplifying fractions when needed (prime factorization) is crucial – user2622016 Nov 08 '13 at 09:43
  • 4
    @user2622016 just divide by the GCD. Prime factorization is massive overkill. – harold Nov 08 '13 at 09:44
  • @user2622016 yes, you should DIY. – Ahmed KRAIEM Nov 08 '13 at 09:44
  • @harold you're right, one should use Euclid's algorithm for simplifying a quotient – user2622016 Nov 08 '13 at 10:19
  • There's the [BigRationalLibrary](https://www.nuget.org/packages/BigRationalLibrary/) on NuGet. – dharmatech Aug 04 '15 at 20:43

0 Answers0