PDA

View Full Version : How to get rid of duplicated double values from QList?



code_err
22nd February 2012, 18:39
Want to create a list of double values but whatever i do seems not to work, every time i get list with duplicated values on it.

Code below should create a list with all intervals between values from oldList, oldList is ascending and contains duplicated values.

QList<double> newList;

for(int i = 1; i < oldList.count(); ++i)
{
for(int j = 0; j < oldList.count() - i; ++j)
{
value = oldList.at(j + i) - oldList.at(j);
if(!newList.contains(value))
{
newList << value;
}
}
}

Is this code correct?

...probably it's something stupid but can't see any error here.

ChrisW67
23rd February 2012, 01:11
Welcome to the world of the floating point approximation. In double precision floating point 0.6 - 0.5 != 0.2 - 0.1 because only 0.5 has an exact representation in binary floating point. If you look at the decimal approximation of the difference to some small number of digits you will see them as equal when their underlying binary representation is not. Have a read here (http://floating-point-gui.de/)

For example:


QList<double> oldList;
QList<double> newList;

oldList << 0.0 << 0.1 << 0.2 << 0.31 << 0.5 << 0.6 << 0.76;

for (int i = 1; i < oldList.size(); ++i) {
double value = oldList.at(i) - oldList.at(i-1);
qDebug() << QString("Computed %1 - %2 = %3")
.arg(oldList.at(i), 22, 'f', 20)
.arg(oldList.at(i-1), 22, 'f', 20)
.arg(value, 22, 'f', 20);
if (!newList.contains(value)) {
newList << value;
qDebug() << "Inserted";
}
}

outputs:


"Computed 0.10000000000000000555 - 0.00000000000000000000 = 0.10000000000000000555"
Inserted
"Computed 0.20000000000000001110 - 0.10000000000000000555 = 0.10000000000000000555"
"Computed 0.30999999999999999778 - 0.20000000000000001110 = 0.10999999999999998668"
Inserted
"Computed 0.50000000000000000000 - 0.30999999999999999778 = 0.19000000000000000222"
Inserted
"Computed 0.59999999999999997780 - 0.50000000000000000000 = 0.09999999999999997780"
Inserted
"Computed 0.76000000000000000888 - 0.59999999999999997780 = 0.16000000000000003109"
Inserted
(0.1, 0.11, 0.19, 0.1, 0.16)

code_err
23rd February 2012, 02:11
I would never figure it out. Magical world of floating point you say. So I know now what i am fighting with.