Cumulative standard deviation: Difference between revisions
Content added Content deleted
(→{{header|Smalltalk}}: append SQL) |
(→{{header|SQL}}: all new) |
||
Line 2,754: | Line 2,754: | ||
('std dev = %1' % { sd }) displayNl.</lang> |
('std dev = %1' % { sd }) displayNl.</lang> |
||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
{{works with|Postgresql}} |
|||
<lang SQL>-- the minimal table |
|||
create table if not exists teststd (n double precision not null); |
|||
-- code modularity with view, we could have used a common table expression instead |
|||
create view vteststd as |
|||
select count(n) as cnt, |
|||
sum(n) as tsum, |
|||
sum(power(n,2)) as tsqr |
|||
from teststd; |
|||
-- you can of course put this code into every query |
|||
create or replace function std_dev() returns double precision as $$ |
|||
select sqrt(tsqr/cnt - (tsum/cnt)^2) from vteststd; |
|||
$$ language sql; |
|||
-- test data is: 2,4,4,4,5,5,7,9 |
|||
insert into teststd values (2); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (4); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (4); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (4); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (5); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (5); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (7); |
|||
select std_dev() as std_deviation; |
|||
insert into teststd values (9); |
|||
select std_dev() as std_deviation; |
|||
-- cleanup test data |
|||
delete from teststd; |
|||
</lang> |
|||
With a command like '''psql <rosetta-std-dev.sql''' you will get an output like this: (duplicate lines generously deleted, locale is DE) |
|||
<pre> |
|||
CREATE TABLE |
|||
FEHLER: Relation »vteststd« existiert bereits |
|||
CREATE FUNCTION |
|||
INSERT 0 1 |
|||
std_deviation |
|||
--------------- |
|||
0 |
|||
(1 Zeile) |
|||
INSERT 0 1 |
|||
std_deviation |
|||
--------------- |
|||
1 |
|||
0.942809041582063 |
|||
0.866025403784439 |
|||
0.979795897113272 |
|||
1 |
|||
1.39970842444753 |
|||
2 |
|||
DELETE 8 |
|||
</pre> |
|||
=={{header|Swift}}== |
=={{header|Swift}}== |