mirror of
https://github.com/sqlite/sqlite.git
synced 2025-10-21 11:13:54 +03:00
Added a "stddev()" aggregate function for testing the new user aggregate
function interface. (CVS 393) FossilOrigin-Name: 2198109712ccf988f93db5740a4f248e80fb9f5d
This commit is contained in:
47
src/func.c
47
src/func.c
@@ -16,9 +16,11 @@
|
||||
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
|
||||
** All other code has file scope.
|
||||
**
|
||||
** $Id: func.c,v 1.1 2002/02/24 01:55:17 drh Exp $
|
||||
** $Id: func.c,v 1.2 2002/02/24 17:12:54 drh Exp $
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include "sqlite.h"
|
||||
|
||||
/*
|
||||
@@ -45,6 +47,48 @@ static void lowerFunc(void *context, int argc, const char **argv){
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
** An instance of the following structure holds the context of a
|
||||
** standard deviation computation.
|
||||
*/
|
||||
typedef struct StdDevCtx StdDevCtx;
|
||||
struct StdDevCtx {
|
||||
double sum; /* Sum of terms */
|
||||
double sum2; /* Sum of the squares of terms */
|
||||
int n; /* Number of terms seen so far */
|
||||
};
|
||||
|
||||
/*
|
||||
** Routines used to compute the standard deviation as an aggregate.
|
||||
*/
|
||||
static void *stdDevStep(void *stddev, int argc, char **argv){
|
||||
StdDevCtx *p;
|
||||
double x;
|
||||
if( argc<1 ) return 0;
|
||||
if( stddev==0 ){
|
||||
p = malloc( sizeof(*p) );
|
||||
p->n = 0;
|
||||
p->sum = 0.0;
|
||||
p->sum2 = 0.0;
|
||||
}else{
|
||||
p = (StdDevCtx*)stddev;
|
||||
}
|
||||
x = atof(argv[0]);
|
||||
p->sum += x;
|
||||
p->sum2 += x*x;
|
||||
p->n++;
|
||||
return p;
|
||||
}
|
||||
static void stdDevFinalize(void *stddev, void *context){
|
||||
StdDevCtx *p = (StdDevCtx*)stddev;
|
||||
if( context && p && p->n>1 ){
|
||||
double rN = p->n;
|
||||
sqlite_set_result_double(context,
|
||||
sqrt((p->sum2 - p->sum*p->sum/rN)/(rN-1.0)));
|
||||
}
|
||||
if( stddev ) free(stddev);
|
||||
}
|
||||
|
||||
/*
|
||||
** This file registered all of the above C functions as SQL
|
||||
** functions.
|
||||
@@ -52,4 +96,5 @@ static void lowerFunc(void *context, int argc, const char **argv){
|
||||
void sqliteRegisterBuildinFunctions(sqlite *db){
|
||||
sqlite_create_function(db, "upper", 1, upperFunc);
|
||||
sqlite_create_function(db, "lower", 1, lowerFunc);
|
||||
sqlite_create_aggregate(db, "stddev", 1, stdDevStep, stdDevFinalize);
|
||||
}
|
||||
|
Reference in New Issue
Block a user