# Averaging wrong

Hello
I have been racking my brain over the code on the cistern water meter.

``````case 'B':  // Show average remaining over the past (up to) 30 days
lcd.clear();
if (PeakDepthIndex < 2) {
lcd.print("Not enough data");
break;
}
{
int averageDepth = 0;
for (int i = 0; i <= PeakDepthIndex; i++)
averageDepth /= PeakDepthIndex + 1;

lcd.print(averageDepth);
delay (5000);
}
break;
``````

The code above is not getting me the difference average. It is getting the average measurement. I have tried many different ways but I just can’t figure it out.

That also probably means that the following is also untrue.

``````    case 'D':  // Show days remaining at average daily usage
lcd.clear();
if (PeakDepthIndex < 2) {
lcd.print("Not enough data");
delay(2500);
break;
}
{
int currentDepth = TANK_DEPTH - sonar.convert_cm(sonar.ping_median(10));
int oldestDepthIndex = (PeakDepthIndex > DepthIndex) ? DepthIndex : 0;
// Subtrace the current depth from the oldest depth
averageUsage -= currentDepth;
// Calculate the number of days since the oldest sample
float days = (PeakDepthIndex + 1) / 2.0;
// Calculate the average usage per day
averageUsage /= days;
// Display the current depth divided by the average daily usage
lcd.print(currentDepth / averageUsage);
delay (5000);
}
break;
``````

Any help appreciated.

The code above is not getting me the difference average. It is getting the average measurement. I have tried many different ways but I just can't figure it out.

I don't understand the difference. Don't you just need to subtract from the max value now if you want the difference? Can you show in math (not code) what it is that you are looking for?

I guess I don't understand what you want exactly. Is it the average deviation from full? Or are you wanting the average change per day?

Well why didn’t you say so! You were measuring the remaining depth twice a day and said you wanted “the average”. I naturally assumed you wanted the average of the measurements because that seemed to be what your original code was doing. The ‘D’ code calculates average daily usage so it can display estimated days remaining. We just take most of ‘D’ and replace ‘B’ with it:

``````case 'B':  // Show average daily usage
lcd.clear();
if (PeakDepthIndex < 2) {
lcd.print("Not enough data");
delay(2500);
break;
}
{
int currentDepth = TANK_DEPTH - sonar.convert_cm(sonar.ping_median(10));
int oldestDepthIndex = (PeakDepthIndex > DepthIndex) ? DepthIndex : 0;
// Subtrace the current depth from the oldest depth