Standard Deviation for SQLite

后端 未结 10 700
生来不讨喜
生来不讨喜 2020-12-14 08:05

I\'ve searched the SQLite docs and couldn\'t find anything, but I\'ve also searched on Google and a few results appeared.

Does SQLite have any built-in Standard Devi

10条回答
  •  春和景丽
    2020-12-14 08:52

    added some error detection in the python functions

    class StdevFunc:
        """
        For use as an aggregate function in SQLite
        """
        def __init__(self):
            self.M = 0.0
            self.S = 0.0
            self.k = 0
    
        def step(self, value):
            try:
                # automatically convert text to float, like the rest of SQLite
                val = float(value) # if fails, skips this iteration, which also ignores nulls
                tM = self.M
                self.k += 1
                self.M += ((val - tM) / self.k)
                self.S += ((val - tM) * (val - self.M))
            except:
                pass
    
        def finalize(self):
            if self.k <= 1: # avoid division by zero
                return none
            else:
                return math.sqrt(self.S / (self.k-1))
    

提交回复
热议问题