org.apache.commons.lang3.math.Fraction Example
Hi folks, Today we are going to talk about Fractions
from org.apache.commons.lang3.math
package. This api provides us with capabilities to handle operations on fractions. I wrote a nice and simple java program demonstrating the application of this api. If you are already a java programmer and if you have tried dividing two numbers with different datatypes, you would have encountered implicit conversion of return value which results in ambiguous results, this class is highly effective in addressing those kinds of issues since you represent the fraction as a single unit.Enough said, lets have fun with Fractions !!!
Download this library here or Maven Repository:
<groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version>
Here is an example on how to go about using this Library.
1. Example
FractionExample.java
package com.javacodegeek; import org.apache.commons.lang3.math.Fraction; public class FractionExample { public static void main(String[] args)throws Exception { operations(); comparisons(); conversions(); extractions(); simpletransformations(); } public static void operations(){ System.out.println("OPERATIONS"); Fraction fraA = Fraction.FOUR_FIFTHS; System.out.println("fraA="+fraA); Fraction fraB = Fraction.getFraction(6, 5); System.out.println("fraB= "+fraB); Fraction AaddB = fraA.add(fraB); System.out.println("Additon: fraA+fraB = "+AaddB); Fraction AxB=fraA.multiplyBy(fraB); System.out.println("MultiplyBy: fraAxfraB = "+AxB); Fraction Apow2 = fraA.pow(2); System.out.println("A power 2: "+Apow2); Fraction AdivB = fraA.divideBy(fraB); System.out.println("A divide by B: "+AdivB); Fraction AminusB = fraA.subtract(fraB); System.out.println("A-B: "+AminusB); } public static void comparisons(){ System.out.println("\nCOMPARISONS"); Fraction fraA = Fraction.FOUR_FIFTHS; Fraction fraB = Fraction.getFraction(6, 5); System.out.println("fraA="+fraA); System.out.println("fraB= "+fraB); int res = fraA.compareTo(fraB); System.out.println("fraA.compareTo(fraB): "+res); boolean boolres = fraA.equals(fraB); System.out.println("fraA.equals(fraB): "+boolres); } public static void conversions(){ System.out.println("\nCONVERSIONS"); Fraction fraA = Fraction.FOUR_FIFTHS; System.out.println("fraA: "+ fraA); double fraAdouble = fraA.doubleValue(); System.out.println("fraA.doubleValue() : "+fraAdouble); float fraAfloat = fraA.floatValue(); System.out.println("fraA.floatValue() : "+fraAfloat); float fraAint = fraA.intValue(); System.out.println("fraA.intValue(): "+fraAint); Fraction frastrMixed = Fraction.getFraction("10 5/7"); System.out.println("Fraction.getFraction(\"10 5/7\"): "+frastrMixed); Fraction frastr = Fraction.getFraction("5/7"); System.out.println("Fraction.getFraction(\"5/7\"): "+frastr); Fraction fraDb = Fraction.getFraction(44.44); System.out.println("Fraction.getFraction(44.44): "+fraDb); Fraction fraND = Fraction.getFraction(6,7); System.out.println("Fraction.getFraction(6,7): "+fraND); Fraction fraWND = Fraction.getFraction(7,8,9); System.out.println("Fraction.getFraction(7,8,9): "+fraWND); } public static void extractions(){ System.out.println("\nEXTRACTIONS"); Fraction fraA = Fraction.FOUR_FIFTHS; System.out.println("fraA: "+fraA); System.out.println("getDenominator(): "+fraA.getDenominator()); System.out.println("getNumerator(): "+ fraA.getNumerator()); System.out.println("getProperNumerator(): "+fraA.getProperNumerator()); System.out.println("getProperWhole(): "+fraA.getProperWhole()); System.out.println("toProperString(): "+fraA.toProperString()); } public static void simpletransformations(){ System.out.println("\nSIMPLETRANSFORAMTIONS"); Fraction fraA = Fraction.FOUR_FIFTHS; System.out.println("fraA: "+fraA); System.out.println("fraA.negate().abs(): "+fraA.negate().abs()); System.out.println("fraA.negate(): "+fraA.negate()); System.out.println("fraA.invert(): "+fraA.invert()); System.out.println("fraA.reduce(): "+fraA.reduce()); System.out.println("fraA.getReducedFraction(20, 30): "+fraA.getReducedFraction(20, 30)); } }
Output
OPERATIONS fraA=4/5 fraB= 6/5 Additon: fraA+fraB = 2/1 MultiplyBy: fraAxfraB = 24/25 A power 2: 16/25 A divide by B: 2/3 A-B: -2/5 COMPARISONS fraA=4/5 fraB= 6/5 fraA.compareTo(fraB): -1 fraA.equals(fraB): false CONVERSIONS fraA: 4/5 fraA.doubleValue() : 0.8 fraA.floatValue() : 0.8 fraA.intValue(): 0.0 Fraction.getFraction("10 5/7"): 75/7 Fraction.getFraction("5/7"): 5/7 Fraction.getFraction(44.44): 1111/25 Fraction.getFraction(6,7): 6/7 Fraction.getFraction(7,8,9): 71/9 EXTRACTIONS fraA: 4/5 getDenominator(): 5 getNumerator(): 4 getProperNumerator(): 4 getProperWhole(): 0 toProperString(): 4/5 SIMPLETRANSFORAMTIONS fraA: 4/5 fraA.negate().abs(): 4/5 fraA.negate(): -4/5 fraA.invert(): 5/4 fraA.reduce(): 4/5 fraA.getReducedFraction(20, 30): 2/3
2. Static constants representing fractions that you can use.
static Fraction FOUR_FIFTHS
is 4/5static Fraction MINUS_ONE
is -1 / 1static Fraction ONE
is 1static Fraction ONE_FIFTH
is 1/5static Fraction ONE_HALF
is 1/2static Fraction ONE_QUARTER
is 1/4static Fraction ONE_THIRD
is 1/3static Fraction THREE_FIFTHS
is 3/5static Fraction THREE_QUARTERS
is 3/4static Fraction TWO
is 2/1static Fraction TWO_FIFTHS
is 2/5static Fraction TWO_QUARTERS
is 2/4static Fraction TWO_THIRDS
is 2/3static Fraction ZERO
is 0
3. Methods associated with fractions are characterized into 5 sections for the sake of explanation.
- Operations
- Comparisons
- Conversions
- Extractions
- Simpletransformations
4. Operations
This category deals with addition,multiplication, power,division,subractions and hence the following methods.
the FractionExample.operations()
method in the above code demonstrates on how to go about using these methods in your program.
Fraction add(Fraction fraction)
Adds the value of this fraction to another, returning the result in reduced form.Fraction divideBy(Fraction fraction)
Divide the value of this fraction by another.Fraction multiplyBy(Fraction fraction)
Multiplies the value of this fraction by another, returning the result in reduced form.Fraction pow(int power)
Gets a fraction that is raised to the passed in power.Fraction subtract(Fraction fraction)
Subtracts the value of another fraction from the value of this one, returning the result in reduced form.
5. Comparisons
This category deals with comparing fractions, hence the following methods.
the FractionExample.comparisons()
method in the above code demonstrates on how to go about using these methods in your program.
int compareTo(Fraction other)
Compares this object to another based on size.boolean equals(Object obj)
Compares this fraction to another object to test if they are equal.
6. Conversions
This category deals with converting numbers,strings into fractions and hence the following methods.
the FractionExample.conversions()
method in the above code demonstrates on how to go about using these methods in your program.
The one method that catches my eye is getFraction(String str) method. because it can not only accept simple fraction like 4/5 but also mixed fraction representation like 10 4/5 which is really handy and ofcourse the fraction object will hold the fraction as is and not reduce it, for that you have another method (reduce()).
Another interesting method is getFraction(double value) which accepts a double and conveniently returns a fraction representation.neat.
double doubleValue()
Gets the fraction as a double.float floatValue()
Gets the fraction as a float.static Fraction getFraction(double value)
Creates a Fraction instance from a double value.static Fraction getFraction(int numerator, int denominator)
Creates a Fraction instance with the 2 parts of a fraction Y/Z.static Fraction getFraction(int whole, int numerator, int denominator)
Creates a Fraction instance with the 3 parts of a fraction X Y/Z.static Fraction getFraction(String str)
Creates a Fraction from a String.int intValue()
Gets the fraction as an int.long longValue()
Gets the fraction as a long.
7. Extractions
This category deals with extracting numbers from a given fraction and hence the following methods.
the FractionExample.extractions()
method in the above code demonstrates on how to go about using these methods in your program.
int getNumerator()
returns the numerator.int getDenominator()
returns the denominator.int getProperNumerator()
returns the proper numerator, always positive.int getProperWhole()
returns the proper whole part of the fraction.String toProperString()
returns the fraction as a proper String in the format X Y/Z(mixed fraction).
8. Simpletransformations
This category deals with transforming a given fraction and hence the following methods.
the FractionExample.simpletransformations()
method in the above code demonstrates on how to go about using these methods in your program.
static Fraction getReducedFraction(int numerator, int denominator)
Creates a reduced Fraction instance with the 2 parts of a fraction Y/Z.Fraction invert()
Gets a fraction that is the inverse (1/fraction) of this one.Fraction negate()
Gets a fraction that is the negative (-fraction) of this one.Fraction pow(int power)
Gets a fraction that is raised to the passed in power.Fraction reduce()
Reduce the fraction to the smallest values for the numerator and denominator, returning the result.
Conclusion
Fraction
class is a simple and elegant api. This can really save a lot of time for programmers who are working with calculations pertaining to fractions.
You can download the source code of this example here: FractionExample.zip