Java doesn't seem to be comparing doubles

I have created a Linked List with inserts, search and delete functions. I also created an iterator for it. Now, suppose I do this:

myList<Integer> test = new myList();
test.insert(30);
test.insert(20);
test.insert(10);
myList.iterator it = test.search(20);
if(it.hasNext())
    System.out.println(it.next());

      

And voila, it works (it prints the value of the element at node, in this case 20). Now if I do this:

myList<Double> test = new myList();
test.insert(30.1);
test.insert(20.1);
test.insert(10.1);
myList.iterator it = test.search(20.1);
if(it.hasNext())
    System.out.println(it.next());

      

This is not the case because the iterator points to null. Here is the implementation of the search function:

public iterator search(T data)
{
    no<T> temp = first;
    while( (temp != null) && (temp.data != data) )
        temp = temp.next;
    return (new iterator(temp));
}

      

Here, as I know, there is something fishy in comparison: if I change part of the above code as follows:

while( (temp != null) && (temp.data != data) )
     System.out.println(temp.data + " " + data);
     temp = temp.next;

      

I can see that it is printing numbers in the list. It prints at some point "20.1 20.1" (for example). So how can I fix this? The function looks correct, but it seems that Java is not comparing numbers correctly.

EDIT: wth, BigDecimal gave me the same problem as well.

EDIT 2: equals () worked, didn't realize there was something else wrong. Unfortunately.

+1


source to share


2 answers


You don't need an operator for this! =. These are comapres links. You need a method .equals()

:

public iterator search(T data)
{
    no<T> temp = first;
    while (!data.equals(temp.data)) {
        temp = temp.next;
    }
    return (new iterator(temp));
}

      

Also pay attention to autoboxing . You may find that test.search(20.1)

boxes 20.1 are Float

not a Double

, which will probably break your comparison. Compare results with test.search(20.1d)

. If I remember correctly, the expression:



new Float(20.1).equals(new Double(20.1))

      

is false.

+2


source


Note that using doubles.equals()

for comparison can lead to errors. uses this as an equality test:Double.equals()

 d1.doubleValue() == d2.doubleValue()

      

Duplicates and floats are approximations of numbers stored in a fixed space in memory.



To properly compare floating point numbers, you need to know that due to the nature of the floats, there will be some error.

see: http://www.google.com/search?q=floating+point+equality

A quick and easy way to compare takes is to use Math.abs(a-b)<ACCEPTABLE_ERROR

where ACCEPTABLE_ERROR may be .000000000001

depending on what you are doing. (Note that this does not apply to cross cases like NaN and INFINITY)

+11


source







All Articles