When you want to do many calculations with big decimals, you often loose a little information. If you were able to use fractions instead of decimals you’re going to safe some information (concerning the result). Well, with this simple class you can do a lot of manipulations using fractions.
Numerator - fraction’s numerator
Denominator - fraction’s denominator
Form - proper / improper (if |fraction|<1 it is proper, else - it’s improper)
You can initialize the fraction by calling its constructor or by direct equality with an integer. There are four constructors:
Fraction f1 = new Fraction(5); // = 5/1
Fraction f2 = 5; // = 5/1
Fraction f3 = new Fraction(1, -5); // = -1/5
Fraction f4 = new Fraction("-1/5"); // = -1/5
I want to add some things else. The denominator of the fraction is always greater than zero. The sign of the fraction is always kept in its numerator. The zero fraction is always represented as 0/1. That means, if you try to change the numerator to zero, the denominator is automatically set to 1.
You can perform sum, subtraction, multiplication and division on this fractions. All operations are possible for both fractions and integers. For example, you can add up an integer to a fraction. The integer is automatically converted to a fraction with denominator 1. You can use a method or a sign for the corresponding operation. Here are some examples:
Fraction sum = new Fraction(1, 4) + 5; // 21/4 sum.Subtract(new Fraction(4, 5)); // 89/20 Fraction mul = new Fraction(1, 4) * 5; // 5/4 mul.DivideBy(5); // 1/4
Fractions can be compared using the standard signs for comparison: <>=. As the denominator of each fraction is positive, we can implement the following method to compare two fractions. Let’s say we have these two fractions ; a/b and c/d, and ‘#’ is one of possible signs between them. a/b # c/d <=> ad # bc.
public int CompareTo(Fraction other)
{
long num1 = this.Numerator * other.Denominator;
long num2 = other.Numerator * this.Denominator;
if (num1 == num2) return 0;
return (num1 > num2) ? 1 : -1;
}
There are some useful methods, that can help you in different situations. For example, you can simplify the the fraction, get its reciprocal or round it to a decimal. I am going to show you the method, which simplifies the fraction.
public void Simplify()
{
int gcm = greatesCommonDivisor(Numerator, Denominator);
Numerator /= gcm;
if (Numerator == 0) Denominator = 1;
else Denominator /= gcm;
}
As you can see, the algorithm finds the greatest common divisor (GCD) of the numerator & denominator and divides both of them by it. I have posted a simple implementation of the Euclidean algorithm for determination of the GCD.
If you encourage any problems with this class, please get in touch with me and I will help you. Well, that’s it! Have fun!
[ Assembly File ] [ Source Code ]
RSS feed for comments on this post · TrackBack URI
Leave a reply