I running this JavaScript to get the average energy for the last 2 days and I seem to get a different result when I query the persistent table for the same item.
The same as all the rules languages, by calling the persistence actions provided by OH core.
I suspect the difference is that OH calculated a time weighted average which takes the time between entries in the database into account.
The SQL average probably is a straight mean that does not take into account the time between entries.
Consider a case where a value is 1, them once minute later becomes 2, then one minute later becomes 10 for the next two hours. A time weighted average is going to be much closer to 10 than 4 because for the bulk of the time, the state was 10.
I don’t understand what you’re saying, but my point by showing the code was to illustrate that it isn’t a “simple average”. There are quite a few things that the code deal with, to figure this out. What if there’s no start or end datapoint where you want the average to start or end? Do you project something then? The code also seems to try to differentiate between past and future, if the “range” you’re averaging somehow crosses the current time (future values would have to be predictions then, obviously). I also see that Riemann sums are used here, I assume it’s to “smooth the values” between the datapoints.
So, in short, it’s no wonder why the results aren’t always the same as a simple, mathematical average. I can’t answer why the calculation is done as it is, I can just state that it is. I assume that there are pretty good reasons for it.