nihilo90
nihilo90

Reputation: 109

Double comparison problems

I'm writing a pitch detection program in Java and compare two doubles in each iteration of a for loop in order to determine the highest magnitude point in a sample array.

The code for this is:

double magnitude = 0.0;
double maxMag = 0.0;

int j = 0;
    for (int i = 0; i < 2640; i += 2) {
        magnitude = calcMag(sample[i], sample[i + 1])
                * (i < outputLength / 2 ? calcMag(sample[i * 2],
                        sample[i * 2 + 1]) : 1.0)
                * (i < outputLength / 3 ? calcMag(sample[i * 3],
                        sample[i * 3 + 1]) : 1.0)
                * (i < outputLength / 4 ? calcMag(sample[i * 4],
                        sample[i * 4 + 1]) : 1.0)
                * (i < outputLength / 5 ? calcMag(sample[i * 5],
                        sample[i * 5 + 1]) : 1.0);

        if (magnitude > maxMag) {
            maxMag = magnitude;
            peakIndex = j;
        }

        j++;
    }

Using a debugger and looking at the variables, the comparison of "magnitude" and "maxMag" works correctly the first time (when maxMag is zero), but from that point on it evaluates to false every time, even when magnitude is in fact greater than maxMag.

Example compared values where (magnitude > maxMag) is false:

magnitude = 2.828262485980501E20

maxMag = 1.3167436120685821E28

I've been looking at this for ages and looked around for potential problems with comparing doubles (I've tried the compare methods of Double to no avail). So now I'm wondering if anyone on here could shed some light on what I might be doing wrong?

Thanks

Upvotes: 1

Views: 466

Answers (4)

james
james

Reputation: 1753

numbers are written in scientific notation here are there decimal representation breakdown

2.828262485980501E20 = 2.828262485980501 * 10^20 = 282826248598050100000

1.3167436120685821E28 = 1.3167436120685821 * 10^28 = 13167436120685821000000000000

So

2.828262485980501E20 < 1.3167436120685821E28

program output is correct.

Upvotes: 1

Luka Klepec
Luka Klepec

Reputation: 542

magnitude=2.28e20 is NOT greater than magMax=1.31e28. The integer after E is the exponent. magMax is in fact 1.31 * 10^28 (1 and 28 zeros) http://en.wikipedia.org/wiki/Scientific_notation

Upvotes: 0

Z&#233;ychin
Z&#233;ychin

Reputation: 4205

magnitude is not greater than maxMag.

magnitude is in the order of 10 to the 20th power. maxMag is in the order of 10 to the 28th power.

Upvotes: 0

theglauber
theglauber

Reputation: 29595

but

maxMag = 1.3167436120685821E28

IS larger than

magnitude = 2.828262485980501E20

Look at the exponents, after the "E"!

Upvotes: 1

Related Questions