Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# compareTo and Arrays.sort

Rich Stepanski
Ranch Hand
Posts: 59
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

Rovas Kram
Ranch Hand
Posts: 135
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 ]

Stefan Wagner
Ranch Hand
Posts: 1923
Do you define equals?
It is strongly recommended (though not required) that natural orderings be consistent with equals.

What is 'temp' and 'num' used for?
Do confuse javaranchers?

If getDenominator returns the private double denominator, you could simplify your code to:

after checking for instance-of.

Rich Stepanski
Ranch Hand
Posts: 59
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?

Ranch Hand
Posts: 1873
Hi,

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.

Regards,
Maulin

Rich Stepanski
Ranch Hand
Posts: 59
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.