Finding the daily average temperature

Hi,

I'm wondering if there is any other (or better) way to find the daily rolling average temperature than this psudocode:


//variables 

x = current temp
y = previous cumulative daily temp
z = new cumulative daily temp

a = average daily temp

i = number of readings taken (increases every reading)

//--------------------------------

i +1 (increase to show how many times we've taken a reading)

z = y + x 

a = z / i

y = z (make previous cumulative daily temp new cumulative daily temp)

My only concern is by some freak event the temperature is zero degrees C all day and it crashes. It's very unlikely to ever see exactly zero as the sensor spits out a float to 2dp, however its still something I'd like to mitigate against.

I'm using an esp32 if that makes any difference.

Thanks

why?

you should use better variables' names...

double cumulativeTemperature = 0;
double currentTemperature = 0;
double averageTemperature = 0;
unsigned long numberOfMeasures = 0;

double getTemperature() {
  return ...
}

void setup() {
  ...
}

void loop() {
  currentTemperature = getTemperature();
  cumulativeTemperature += currentTemperature;
  numberOfMeasures += 1;
  averageTemperature = cumulativeTemperature / numberOfMeasures;
  // print currentTemperature
  // print average
}

that would give you the average from the moment you start your ESP and until your overflow the double or the unsigned long

usually you don't want an average over such a long period, you just want to average the last 10 readings or something like that or have a running average

1 Like

Please do yourself a favor and give your variables a proper name...
Either z or y is not needed....

sum = sum + cur_temp;

What would be the problem if it is 0 degrees all day?
How many floats will you add? Every minute or every second? You might loose accuracy if sum >> cur_temp.

1 Like

You beat me...

The average of zero is zero. No problem!

1 Like

Hi both,

The variables will be named properly when I come to write the code, I was looking at the method rather than the variable names.

I did forget to say I'd only be taking a reading every 30min, so 48 readings a day then the counter would reset. The method seems sound to me thank you.

The issue with 0 all day is, I thought, we don't like dividing into or by 0?

Thanks both

Sweet :+1:

Don't try to calculate the average before you have any readings. :wink:

(0+0+0+0+0+….+0)/48 = ?

You divide by the number of readings, not by the sum of the temperatures

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.