Skip to content

Commit

Permalink
findTopCellItem() handle underflow (f20-3)
Browse files Browse the repository at this point in the history
  • Loading branch information
Explorer09 committed Feb 7, 2024
1 parent 837b61b commit ac00bc6
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions Meter.c
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand All @@ -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;
Expand Down

0 comments on commit ac00bc6

Please sign in to comment.