PDA

View Full Version : Program not finding an existing double in a QList<double>



aarelovich
9th May 2011, 20:58
This is the code that is giving me a hard time.

The function is called four times, each changing only the value parameter



bool ReservedWord::belongsToList(qreal start, qreal end, qreal step, qreal value){
QList<qreal> list;
list << start;
while (list.last() <= end){
list << list.last() + step;
}
list.removeLast();

qDebug() << "Checking for" << value << "on list" << list << "and the answer is" << list.contains(value);
return list.contains(value);
}


The program output is:

Checking for 4.2 on list (4, 4.2, 4.4, 4.6, 4.8, 5, 5.2, 5.4) and the answer is true
Checking for 4.4 on list (4, 4.2, 4.4, 4.6, 4.8, 5, 5.2, 5.4) and the answer is true
Checking for 4.6 on list (4, 4.2, 4.4, 4.6, 4.8, 5, 5.2, 5.4) and the answer is false
Checking for 5.2 on list (4, 4.2, 4.4, 4.6, 4.8, 5, 5.2, 5.4) and the answer is false

The objective is to define a numbers list by defining it's beginning, it's end and a certain step. Then checking to see if a value belongs to the list. In two cases the value is clearly there but the it is not found.

Any ideas of what is wrong?

franz
9th May 2011, 21:45
Double values suffer from machine precision. That means that 4.6 does not necessarily have to be exactly equal to 4.6. You should use another approach using qFuzzyCompare(), that takes into account this issue. Maybe you can write a template specialization for it, but that would mean you have that behavior throughout your program, and requires you to do template magic.



bool SomeClass::listContains(qreal value) const
{
foreach (qreal v, theList) {
if (qFuzzyCompare(value, v))
return true;
}
return false;
}

aarelovich
9th May 2011, 21:59
Yeah, I figured the machine precision thing. What I did not know is how to solve it. Since this part doesn't have to be efficient at all, I solved it by turning Everything to strings and comparing then. But I'll take the qFuzzyCompare into account.

Thank you very much.