Problem to detect minimum value of a negative number
-
Hi guys,
I'm trying to detect the maximum and the minimum y value from a plot. The maximum is ok. But I can not detect the correct negative number. I guess the problem may be the variable type, however I could not solve.
My code is:
auto plot10 = ui->customPlot_10; double y_max = 0.0; double y_min = 0.0; QVector<double> x(256), y(256); for (int i=0; i<x.size(); ++i) { x[i] = plot10->graph(0)->data()->at(i)->key; y[i] = plot10->graph(0)->data()->at(i)->value; if (y[i]>=y_max) y_max = y[i]; if (y[i]<=y_min) y_min = y[i]; qDebug () << "Min i: " << y_min; qDebug () << "Max i: " << y_max; }
The Debug result shows that the code ignore the number signal, as you can see:
Min i: -0.14 Min i: -0.14 Min i: -0.14 Min i: -0.14 Min i: 0.18 Min i: 0.22 Min i: 0.26 Min i: 0.28 Min i: 0.31 Min i: 0.33 Min i: 0.34 //...
Could someone help me?
Cheers,
-
Hi
I would start by doingqDebug () << "value: " << y[i];
to see the input data.You are using doubles so it should not be the issues since its mostly doing ==
(is equal that can be tricky )That said
You could use
#include <algorithm>
double min = *std::min_element(vec.constBegin(), vec.constEnd());
double max = *std::max_element(vec.constBegin(), vec.constEnd());
If you build the vector first. -
HI, I don't think this will work with both <= and >= conditions. They should be just < or > and you should init them with y_max as a smaller value than the range you expect and y_min with a larger value than the range you expect.
y_max = REAL_MIN; // or something else very small y_min = REAL_MAX; // or something else very large ... if (y[i]>y_max) y_max = y[i]; if (y[i]<y_min) y_min = y[i];
should work better.
-
Don't reinvent the wheel
QSharedPointer<QCPGraphDataContainer > graphData = ui->customPlot_10->graph(0)->data(); const double y_max = std::max_element(graphData->cbegin(),graphData->cend(),[](const QCPGraphData& a, const QCPGraphData& b)->bool{return a.value<b.value;})->value; const double y_min = std::min_element(graphData->cbegin(),graphData->cend(),[](const QCPGraphData& a, const QCPGraphData& b)->bool{return a.value<b.value;})->value; const double x_max = std::max_element(graphData->cbegin(),graphData->cend(),[](const QCPGraphData& a, const QCPGraphData& b)->bool{return a.key<b.key;})->key; const double x_min = std::min_element(graphData->cbegin(),graphData->cend(),[](const QCPGraphData& a, const QCPGraphData& b)->bool{return a.key<b.key;})->key;
-
Thank you guys your solutions are great and i'm gonna to use in different applications!!
Cheers,