diff --git a/Meter.c b/Meter.c index e2571f32f..08b283ba4 100644 --- a/Meter.c +++ b/Meter.c @@ -386,7 +386,6 @@ static uint8_t GraphMeterMode_findTopCellItem(const Meter* this, double scaledTo assert(topCell < graphHeight); double valueSum = 0.0; - bool maxValueIsArea = false; double maxValue = 0.0; uint8_t topCellItem = this->curItems - 1; for (uint8_t i = 0; i < this->curItems && valueSum < DBL_MAX; i++) { @@ -410,35 +409,33 @@ static uint8_t GraphMeterMode_findTopCellItem(const Meter* this, double scaledTo // Find the item that occupies the largest area of the top cell. // Favor item with higher index in case of a tie. - double area = (value / scaledTotal) * (double)(int)graphHeight; - assert(area >= 0.0); - - if (topCellItem > i) { - assert(!maxValueIsArea); - assert(maxValue <= 0.0); - + if (topCell > 0) { double topPoint = (valueSum / scaledTotal) * (double)(int)graphHeight; assert(topPoint >= 0.0); - if (topCell > 0 && !(topPoint > (double)(int)topCell)) + if (!(topPoint > (double)(int)topCell)) continue; - if (area > topPoint - (double)(int)topCell) { - maxValueIsArea = true; - maxValue = topPoint - (double)(int)topCell; - } else { - maxValue = value; - } - topCellItem = i; - } else if (maxValueIsArea) { + double area = (value / scaledTotal) * (double)(int)graphHeight; + assert(area >= 0.0); + + if (area > topPoint - (double)(int)topCell) + area = topPoint - (double)(int)topCell; + + // Note: The FP default rounding mode (i.e. to nearest) ensures any + // "area" that could win to have a number at least (DBL_EPSILON / 2). + if (area >= maxValue) { - maxValueIsArea = false; + maxValue = area; + topCellItem = i; + } + } else { + // Compare "value" directly. It is possible for an "area" to + // underflow here, and still wins as the largest area. + if (value >= maxValue) { maxValue = value; topCellItem = i; } - } else if (value >= maxValue) { - maxValue = value; - topCellItem = i; } } return topCellItem;