Reputation: 6413
There is this problem with C# decimal type:
Console.WriteLine( 1m/3 + 1m/3 == 2m/3 );
False
It can represent numbers exactly only when dividing by 2 or 5, otherwise result could be repeating decimal number.
As mentioned on Stack Overflow before (C# Rational arithmetic), implementing something which stores two decimals, numerator and denominator, and performs multiplications and divisions exactly is quite possible. It can simplify fractions when needed using Euclid's algorithm. Some explicit conversion to double or decimal should also be implemented.
There are some rational quotients implementations presented here and here. There is also a Microsoft Solver Foundation structure Rational.
How decimal
in C# is implemented and is it possible to copy this implementation and modify it to handle repeating decimal
s ?
There are some trials related to repeating decimals presented in SO answers here and here
Upvotes: 0
Views: 247
Reputation: 1500365
decimal
is implemented as a significand, sign and exponent, basically - a floating point number, where the "point" is a decimal point instead of a binary point (as per float
and double
). See my article on the topic for more details. (Note that unlike float
and double
, decimal
isn't normalized - so it will retain trailing insignificant zeroes, for example.)
If you wanted to create your own RationalNumber
type you could do so, but you wouldn't want to start with the source code to decimal
- and you wouldn't be able to change the meaning of decimal
to mean your type, either.
Upvotes: 9