I'm new to using the comparable interface, so hopefully this has a simple fix... I've created a class Fraction used to store fractions and it implements the comparable interface. I overrided the compareTo method. With this code...
I call Arrays.sort(arrayOfFractions) and then display the array. It seems to partially work. It puts most of the fractions in order , but some are just slightly off. I'm not familar with this interface at all - am I missing something? Thanks for any help
It looks like you understand how to use the Comparable interface properly. Maybe there's some precision being loss. Maybe you can try finding a common denominator and then just comparing integers. [ September 13, 2004: Message edited by: Rovas Kram ]
num and temp were an accident - made some changes and didn't remove them.
when I create the fractions I reduce if possible. I've tested that pretty well and it doesn't seem to have bugs (I've printed original values before making the fractions, and then printed the actual fractions after reduction)
I dont define equals - but it seemed the Double.compareTo() would return 0 if they were equal.
Both the numerator and denominator are int 's. Could this be my loss of precision?
I guess you have the problem due to double's precision. When you do divison and get f1 and f2 even if those two set of values are same i.e. Numerator and Denominator then also their divison values could differ by some very small fraction and in that case Double's compareTo() will not return 0 (as two doubles are different).
I would suggest following way of impl,
Observe the followings, 1. We use STATIC method compare() to save Unnecessary object creation 2. We only do divison if neccessary
This should work for you.
Joined: Aug 24, 2004
I made your changes to avoid the extra static calls. However I've found my problem and it is with precision. When I divide an int by an int - my doubles are all ints without decimals. Which is a rather large loss of precision.. I cast each division to double and everything is working good now. Thanks for the help everyone.