Calculate Standard Deviation

19

4

Challenge

Given a list of numbers, calculate the population standard deviation of the list.

Use the following equation to calculate population standard deviation:

Input

The input will a list of integers in any format (list, string, etc.). Some examples:

56,54,89,87
67,54,86,67

The numbers will always be integers.

Input will be to STDIN or function arguments.

Output

The output must be a floating point number.

Rules

You may use built in functions to find the standard deviation.

Your answer can be either a full program or a function.

Examples

10035, 436844, 42463, 44774 => 175656.78441352615

45,67,32,98,11,3 => 32.530327730015607

1,1,1,1,1,1 => 0.0

Winning

The shortest program or function wins.

Leaderboard

var QUESTION_ID=60901,OVERRIDE_USER=30525;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

Beta Decay

Posted 2015-10-15T17:11:46.067

Reputation: 21 478

1You mean the output must be a floating point OR integer? – Mutador – 2015-10-15T18:01:49.227

3I think most build-in standard deviation functions calculates the the sample standard deviation. – Mutador – 2015-10-15T18:21:11.420

What about if input list is void?175656.78441352615 result to me 175656.78441352614 – RosLuP – 2017-04-24T19:16:17.150

@RosLuP You don't have to worry about that – Beta Decay – 2017-04-24T19:29:48.307

Does the code need to have some provision for taking input? For example, in Matlab you could do std(x), where x is the list of numbers. So do I need to have code that asks the user for input (prompt, etc)? – a13a22 – 2017-12-25T22:09:28.220

1@a13a22 As per PPCG's standard rules, you are fine to take input via function arguments – Beta Decay – 2017-12-26T18:06:04.017

Answers

18

Clip, 3

.sk

.s is the standard deviation, k parses the input in the form {1,2,3}.

Ypnypn

Posted 2015-10-15T17:11:46.067

Reputation: 10 485

What formula is used for the standard deviation? I could not find it int he reference. – flawr – 2015-10-15T18:11:04.310

@flawr It's this chart, towards the bottom.

– Conor O'Brien – 2015-10-15T18:13:04.813

@CᴏɴᴏʀO'Bʀɪᴇɴ I saw that, but there is no formula given. – flawr – 2015-10-15T18:14:43.913

@flawr Oh, I see. Perhaps then it is up to the interpreter, if such a thing exists. – Conor O'Brien – 2015-10-15T18:15:14.763

2

@CᴏɴᴏʀO'Bʀɪᴇɴ I found it here on line 493, it seems to be ok!

– flawr – 2015-10-15T18:17:11.453

@flawr That's great! Nice reference. Worries aside, this is a fantastic answer. – Conor O'Brien – 2015-10-15T18:56:00.057

11

Mathematica, 24 22 bytes

Nice, Mathematica has a built-in StandardDevi... oh... that computes the sample standard deviation, not the population standard deviation.

But what if we use Variance... oh... same deal.

But there is yet another related built-in:

CentralMoment[#,2]^.5&

Yay. :)

This also works for 22 bytes:

Mean[(#-Mean@#)^2]^.5&

And this for 27:

N@RootMeanSquare[#-Mean@#]&

Martin Ender

Posted 2015-10-15T17:11:46.067

Reputation: 184 808

10

Octave, 14 bytes

g=@(a)std(a,1)

Try it on ideone.

beaker

Posted 2015-10-15T17:11:46.067

Reputation: 2 349

2You can save two bytes by removing g= since the function handle doesn't need a name to be a valid submission. – Alex A. – 2015-10-20T00:50:28.130

10

kdb+, 3 bytes

dev

One of the APL derviates had to have this as a built-in.

Test run

q)dev 56, 54, 89, 87
16.53028
q)f:dev
q)f 10035, 436844, 42463, 44774
175656.8
q)f 45,67,32,98,11,3
32.53033

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

8

Dyalog APL, 24 23 21 20 19 17 bytes

*∘.5∘M×⍨-M×M←+/÷≢

This defines an unnamed, monadic function train, which is equivalent to the following function.

{.5*⍨M(×⍨⍵)-M⍵×(M←{(+/⍵)÷≢⍵})⍵}

Try them online on TryAPL.

How it works

The code consists of several trains.

M←+/÷≢

This defines a monadic 3-train (fork) M that executes +/ (sum of all elements) and (length) for the right argument, then applies ÷ (division) to the results, returning the arithmetic mean of the input.

M×M

This is another fork that applies M to the right argument, repeats this a second time, and applies × (product) to the results, returning μ2.

×⍨-(M×M)

This is yet another fork that calculates the square of the arithmetic mean as explained before, applies ×⍨ (product with itself) to the right argument, and finally applies - (difference) to the results.

For input (x1, …, xN), this function returns (x1 - μ2, …, xN - μ2).

*∘.5∘M

This composed function is applies M to its right argument, then *∘.5. The latter uses right argument currying to apply map input a to a*0.5 (square root of a).

(*∘.5∘M)(×⍨-(M×M))

Finally, we have this monadic 2-train (atop), which applies the right function first, then the left to its result, calculating the standard deviation as follows.

formula

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

5

CJam, 24 22 21 bytes

q~_,_@_:+d@/f-:mh\mq/

Thanks to @aditsu for golfing off 1 byte!

Try it online in the CJam interpreter.

How it works

q~                    e# Read all input and evaluate it.
  _,                  e# Copy the array and push its length.
    _@                e# Copy the length and rotate the array on top.
      _:+d            e# Copy the array and compute its sum. Cast to Double.
          @/          e# Rotate the length on top and divide the sum by it.
            f-        e# Subtract the result (μ) from the array's elements.
              :mh     e# Reduce by hypotenuse.
                      e# a b mh -> sqrt(a^2 + b^2)
                      e# sqrt(a^2 + b^2) c mh -> sqrt(sqrt(a^2 + b^2)^2 + c^2)
                      e#                           = sqrt(a^2 + b^2 + c^2)
                      e# ⋮
                 \mq/ e# Divide the result by the square root of the length.

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

I think you can convert just the length to double – aditsu quit because SE is EVIL – 2015-10-15T20:01:53.650

@aditsu Of course. Thanks! – Dennis – 2015-10-15T20:05:16.797

5:mh is genius btw :) – aditsu quit because SE is EVIL – 2015-10-15T20:06:48.863

2Reduce by hypotenuse. isn't something you see every day. – lirtosiast – 2015-10-16T03:48:07.643

5

R, 41 40 39 36 30 28 bytes

code

Thanks to beaker, Alex A. and MickyT for much bytes.

cat(sd(c(v=scan(),mean(v))))   

old codes

v=scan();n=length(v);sd(v)/(n/(n-1))**0.5
m=scan();cat(sqrt(sum(mean((m-mean(m))^2))))
m=scan();cat(mean((m-mean(m))^2)^.5) 

This should yield the population standard deviation.

Mutador

Posted 2015-10-15T17:11:46.067

Reputation: 1 361

I think this does not output the required result: http://stats.stackexchange.com/a/25961/43450

– flawr – 2015-10-15T18:06:45.037

1I don't know R, but would it be possible to augment the input array with the mean of the array? It seems that might be shorter. – beaker – 2015-10-15T18:45:43.193

@beaker I am not sure, I think it is not possible but I am no expert. – Mutador – 2015-10-15T18:56:14.447

1On this site we typically can't assume a REPL environment unless explicitly allowed by the question. Thus in this case you'll need to use cat to print to the console. – Alex A. – 2015-10-15T18:57:13.400

1Also, R uses ^ for exponentiation, which is a byte shorter than **. – Alex A. – 2015-10-15T18:57:38.727

@AlexA. Thats true! I don't know how but I had some problems with ^ a while ago and totaly forgot it, thank you Alex. – Mutador – 2015-10-15T18:59:40.030

1You don't need to sum the mean since mean returns a scalar; sum has no effect. 36 bytes: x=scan();cat(mean((x-mean(x))^2)^.5) – Alex A. – 2015-10-15T18:59:43.850

@MickyT that doesn't seems to work, it says it can't find x – Mutador – 2015-10-15T19:05:15.297

1@AndréMuta apologies, when I tested it I had an X hanging around. – MickyT – 2015-10-15T19:06:15.573

@AlexA. too much information, thanks for the edit. – Mutador – 2015-10-15T19:07:22.117

The scan can be moved in, but there are no savings unfortunately cat(mean(((x=scan())-mean(x))^2)^.5) since it would need to be bracketed. – MickyT – 2015-10-15T19:10:45.293

Well you taught me something new at least @MickyT. ;) – Mutador – 2015-10-15T19:12:37.580

1@AndréMuta I was talking about doing something like this: v <- c(v,mean(v)) (I think this is correct) and then taking the standard deviation of the updated list. – beaker – 2015-10-15T19:29:07.963

@beaker you are a genious. – Mutador – 2015-10-15T19:33:04.160

@beaker very nice – MickyT – 2015-10-15T19:54:45.000

5

Pyth, 20 19 17 13 bytes

@.O^R2-R.OQQ2

Thanks to @FryAmTheEggman for golfing off 4 bytes!

Try it online.

How it works

        .OQ    Compute the arithmetic mean of the input (Q).
      -R   Q   Subtract the arithmetic mean of all elements of Q.
   ^R2         Square each resulting difference.
 .O            Compute the arithmetic mean of the squared differences.
@           2  Apply square root.

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

I like how the decomposition of a Pyth program looks like a skewed parabola. – Conor O'Brien – 2015-10-19T14:51:25.523

4

TI-BASIC, 7 bytes

stdDev(augment(Ans,{mean(Ans

I borrowed the algorithm to get population standard deviation from sample standard deviation from here.

The shortest solution I could find without augment( is 9 bytes:

stdDev(Ans√(1-1/dim(Ans

lirtosiast

Posted 2015-10-15T17:11:46.067

Reputation: 20 331

I agree with AndréMuta, this does not produce the required result, see here.

– flawr – 2015-10-15T18:27:22.347

1@AndréMuta @flawr TI's builtin stdDev( calculates the sample SD; stdDev(augment(Ans,{mean(Ans computes the population SD. That's on the page you linked to. – lirtosiast – 2015-10-15T18:29:49.257

4

APL, 24 bytes

{.5*⍨+/(2*⍨⍵-+/⍵÷≢⍵)÷≢⍵}

A little different approach than Dennis' Dyalog APL solution. This should work with any APL implementation.

This creates an unnamed monadic function that computes the vector (x - µ)2 as 2*⍨⍵-+/⍵÷≢⍵, divides this by N (÷≢⍵), takes the sum of this vector using +/, and then takes the square root (.5*⍨).

Try it online

Alex A.

Posted 2015-10-15T17:11:46.067

Reputation: 23 761

Not every APL implementation supports {dfns}, , or . However, every version supports R←F Y R←(+/((Y-+/Y÷⍴Y)*2)÷⍴Y)*.5 – Adám – 2015-12-13T07:25:27.337

4

Julia, 26 19 bytes

x->std([x;mean(x)])

This creates an unnamed function that accepts an array and returns a float.

Ungolfed, I guess:

function f(x::Array{Int,1})
    # Return the sample standard deviation (denominator N-1) of
    # the input with the mean of the input appended to the end.
    # This corrects the denominator to N without affecting the
    # mean.
    std([x; mean(x)])
end

Alex A.

Posted 2015-10-15T17:11:46.067

Reputation: 23 761

3

Python 3.4+, 30 bytes

from statistics import*;pstdev

Imports the builtin function pstdev, e.g.

>>> pstdev([56,54,89,87])
16.53027525481654

Sp3000

Posted 2015-10-15T17:11:46.067

Reputation: 58 729

I think just pstdev after the first line is ok? I believe xnor did that a while ago with sum. It sort of makes sense wrt how anonymous lambdas would be used i.e. p=pstdev or map(pstdev, [...]) – FryAmTheEggman – 2015-10-15T18:52:26.150

I was going to say the same thing. Meta posts seem to support just putting a function literal. – xnor – 2015-10-15T19:36:47.993

I think you still need to write the literal pstdev though, like from statistics import*;pstdev. Otherwise, this could be any function from that library. – xnor – 2015-10-16T03:12:13.407

@xnor Edited. tbh I'm not really sure about the ruling on these situations... – Sp3000 – 2015-10-16T03:30:25.147

Maybe a meta question would be helpful? :) – Beta Decay – 2015-10-16T16:41:47.570

3

Haskell, 61 bytes

d n=1/sum(n>>[1])
f a=sqrt$d a*sum(map((^2).(-)(d a*sum a))a)

Straightforward, except maybe my custom length function sum(n>>[1]) to trick Haskell's strict type system.

nimi

Posted 2015-10-15T17:11:46.067

Reputation: 34 639

You can use sum(1<$n) and <$> for map. – Laikoni – 2017-10-30T12:03:05.270

It just occurred to me that those functions might not be present because of an older GHC version at the time of this answer, but according to this tip they were introduced to prelude in March 2015, and the site policy has changed anyway to allow newer language features.

– Laikoni – 2017-10-30T12:07:34.317

2

JavaScript (ES6), 73 bytes

a=>Math.sqrt(a.reduce((b,c)=>b+(d=c-eval(a.join`+`)/(l=a.length))*d,0)/l)

Mwr247

Posted 2015-10-15T17:11:46.067

Reputation: 3 494

@BetaDecay Regarding precision of the output? My original actually didn't have that correct, and I fixed it right after, only to discover floating point was ok hehe... So is it good now as it is? – Mwr247 – 2015-10-15T18:01:24.053

Yeah that's fine :) – Beta Decay – 2015-10-15T18:01:43.397

7Psst... you can shave off 5 bytes by using this summing method eval(a.join\+`)instead ofa.reduce((e,f)=>e+f)` – George Reith – 2015-10-15T22:31:52.163

@GeorgeReith Nice trick! I'm going to have to remember that one for later... – Mwr247 – 2015-10-16T14:57:56.123

2

J, 18 bytes

[:%:@M*:-M*M=:+/%#

This is a direct translation of my APL answer to J.

Try it online!

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

I had no idea M was a predefined built in. – Conor O'Brien – 2016-08-06T04:31:40.393

It isn't. M=:+/%# is an inline function definition. – Dennis – 2016-08-06T04:32:36.927

But it's predefined, right? Perhaps builtin is the wrong term – Conor O'Brien – 2016-08-06T04:33:44.893

No, it's not predefined. M=:+/%# saves the verb +/%# in M, then calls it. – Dennis – 2016-08-06T04:36:56.693

I am sorry XD I didn't see the last part – Conor O'Brien – 2016-08-06T04:37:30.860

That link doesn't work anymore. Could you perhaps move it to https://tio.run/nexus/J ? I would, but I don't know enough about J to setup the input correctly/verify it still works.

– James – 2017-01-16T18:06:43.757

@DJMcMayhem Done. Thanks for the heads-up. – Dennis – 2017-01-16T18:36:21.763

Haha, no problem. I came across it here.

– James – 2017-01-16T18:37:32.770

Yes, I saw. The post author gets a notification when an edit it suggested. – Dennis – 2017-01-16T18:38:25.390

2

Jelly, non-competing

11 bytes This answer is non-competing, since it uses a language that postdates the challenge.

S÷L
Dz_²ÇN½

This is a direct translation of my APL answer to Jelly. Try it online!

How it works

S÷L        Helper link. Argument: z (vector)

S          Compute the sum of z.
  L        Compute the length of z.
 ÷         Divide the former by the latter.
           This computes the mean of z.

Dz_²ÇN½    Main link. Argument: z (vector)

Ç          Apply the previous link, i.e., compute the mean of z.
 ²         Square the mean.
   ²       Square all number in z.
  _        Subtract each squared number from the squared mean.
    Ç      Take the mean of the resulting vector.
     N     Multiply it by -1.
      ½    Take the square root of the result.

Dennis

Posted 2015-10-15T17:11:46.067

Reputation: 196 637

1

Simplex v.0.5, 43 bytes

Just 'cuz. I really need to golf this one more byte.

t[@u@RvR]lR1RD@wA@T@{j@@SR2ERpR}u@vR@TR1UEo   
t[      ]                                     ~~ Applies inner function to entire strip (left-to-right)
  @                                           ~~ Copies current value to register
   u                                          ~~ Goes up a strip level
    @                                         ~~ Dumps the register on the current byte
     R                                        ~~ Proceeds right (s1)
      v                                       ~~ Goes back down
       R                                      ~~ Proceeds right (s0)
                                              ~~ Go right until an empty byte is found
         lR1RD                                ~~ Push length, 1, and divide.
              @                               ~~ Store result in register (1/N)
               wA                             ~~ Applies A (add) to each byte, (right-to-left)
                 @T@                          ~~ Puts 1/N down, multiplies it, and copies it to the register
                    {          }              ~~ Repeats until a zero-byte is met
                     j@@                      ~~ inserts a new byte and places register on it
                        SR                    ~~ Subtract it from the current byte and moves right
                          2E                  ~~ Squares result
                            RpR               ~~ Moves to the recently-created cell, deletes it, and continues
                                u@v           ~~ takes 1/N again into register
                                   R@T        ~~ multiplies it by the new sum
                                      R1UE    ~~ takes the square root of previous
                                          o   ~~ output as number

Conor O'Brien

Posted 2015-10-15T17:11:46.067

Reputation: 36 228

1

Perl5, 39 38


 16 for the script
+22 for the M switch
+ 1 for the E switch
=39

perl -MStatistics::Lite=:all -E"say stddevp@ARGV" .1 .2 300

Tested in Strawberry 5.20.2.


Oh, but then I realized that you said our answers can be functions instead of programs. In that case,

{use Statistics::Lite":all";stddevp@_}

has just 38. Tested in Strawberry 5.20.2 as

print sub{use Statistics::Lite":all";stddevp@_}->( .1, .2, 300)

msh210

Posted 2015-10-15T17:11:46.067

Reputation: 3 094

1

Prolog (SWI), 119 bytes

Code:

q(U,X,A):-A is(X-U)^2.
p(L):-sumlist(L,S),length(L,I),U is S/I,maplist(q(U),L,A),sumlist(A,B),C is sqrt(B/I),write(C).

Explanation:

q(U,X,A):-A is(X-U)^2.   % calc squared difference of X and U
p(L):-sumlist(L,S),      % sum input list
      length(L,I),       % length of input list
      U is S/I,          % set U to the mean value of input list
      maplist(q(U),L,A), % set A to the list of squared differences of input and mean
      sumlist(A,B),      % sum squared differences list
      C is sqrt(B/I),    % divide sum of squares by length of list
      write(C).          % print answer

Example:

p([10035, 436844, 42463, 44774]).
175656.78441352615

Try it out online here

Emigna

Posted 2015-10-15T17:11:46.067

Reputation: 50 798

0

SmileBASIC, 105 bytes (as a function)

I just noticed it's allowed to be a function. Whoops, that reduces my answer dramatically. This defines a function S which takes an array and returns the population standard deviation. Go read the other one for an explanation, but skip the parsing part. I don't want to do it again.

DEF S(L)N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT RETURN SQR(1/N*T)END

As a program, 212 bytes

Unfortunately, I have to take the input list as a string and parse it myself. This adds over 100 bytes to the answer, so if some input format other than a comma-separated list is allowed I'd be glad to hear it. Also note that because VAL is buggy, having a space before the comma or trailing the string breaks the program. After the comma or at the start of the string is fine.

DIM L[0]LINPUT L$@L I=INSTR(O,L$,",")IF I>-1THEN PUSH L,VAL(MID$(L$,O,I-O))O=I+1GOTO@L ELSE PUSH L,VAL(MID$(L$,O,LEN(L$)-O))
N=LEN(L)FOR I=0TO N-1U=U+L[I]NEXT
U=1/N*U FOR I=0TO N-1T=T+POW(L[I]-U,2)NEXT?SQR(1/N*T)

Ungolfed and explained:

DIM L[0]  'define our array
LINPUT L$ 'grab string from input

'parse list
'could've used something cleaner, like a REPEAT, but this was shorter
@L
I=INSTR(O,L$,",")                 'find next comma
IF I>-1 THEN                      'we have a comma
 PUSH L,VAL(MID$(L$,O,I-O))       'get substring of number, parse & store
 O=I+1                            'set next search location
 GOTO @L                          'go again
ELSE                              'we don't have a comma
 PUSH L,VAL(MID$(L$,O,LEN(L$)-O)) 'eat rest of string, parse & store
ENDIF                             'end

N=LEN(L) 'how many numbers we have

'find U
'sum all of the numbers, mult by 1/N
FOR I=0 TO N-1
 U=U+L[I]
NEXT
U=1/N*U

'calculate our popstdev
'sum(pow(x-u,2))
FOR I=0 TO N-1
 T=T+POW(L[I]-U,2)
NEXT
PRINT SQR(1/N*T) 'sqrt(1/n*sum)

snail_

Posted 2015-10-15T17:11:46.067

Reputation: 1 982

0

Axiom, 137 bytes

m(a:List Float):Complex Float==(#a=0=>%i;reduce(+,a)/#a)
s(a:List Float):Complex Float==(#a=0=>%i;n:=m(a);sqrt(m([(x-n)^2 for x in a])))

The function m() would return the mean of the list in input. Both the functions on error return %i the imaginary constant sqrt(-1). Code for test and results. [but the result if it is ok, it is the real part of one complex number]

(6) -> s([45,67,32,98,11,3])
   (6)  32.5303277300 15604966

(7) -> s([10035,436844,42463,44774])
   (7)  175656.7844135261 4035

(8) -> s([1,1,1,1,1,1])
   (8)  0.0

RosLuP

Posted 2015-10-15T17:11:46.067

Reputation: 3 036

0

Python 3, 49 bytes

lambda l,N:(sum((i-sum(l)/N)**2for i in l)/N)**.5

Try it online!

Takes in l, a list of integers, and N, the number of integers present.

musicman523

Posted 2015-10-15T17:11:46.067

Reputation: 4 472

0

Pyt, 13 bytes

←Đ↔Ł↔е-²Ʃ⇹/√

Implements the formula for standard deviation

mudkip201

Posted 2015-10-15T17:11:46.067

Reputation: 833

0

Python, 57 bytes

lambda l:(sum((x-sum(l)/len(l))**2for x in l)/len(l))**.5

Takes input as a list

Thanks @xnor

Beta Decay

Posted 2015-10-15T17:11:46.067

Reputation: 21 478

I think you can do .5 in place of 0.5 to save a byte. Also do you mean len(x) instead of len(l)? – Alex A. – 2015-10-15T20:19:15.690

@AlexA. Uhh, no I don't think so... – Beta Decay – 2015-10-15T20:30:15.593

1Sorry, got confused. Disregard the x and l nonsense. But you can still do .5 to save a byte. – Alex A. – 2015-10-15T20:31:16.660

1@BetaDecay It's shorter to use a list-comp than to map a lambda: sum((x-sum(l)/len(l))**2for x in l). – xnor – 2015-10-16T03:19:50.130

1A different formulation gave the same length: lambda l:(sum(x*x*len(l)for x in l)-sum(l)**2)**.5/len(l). – xnor – 2015-10-16T03:27:54.093

0

PowerShell, 122

:\>type stddev.ps1
$y=0;$z=$args -split",";$a=($z|?{$_});$c=$a.Count;$a|%{$y+=$_};$b=$y/$c;$a|%{$x+
=(($_-$b)*($_-$b))/$c};[math]::pow($x,0.5)

explanation

<#
$y=0                            init
$z=$args -split","              split delim ,
$a=($z|? {$_})                  remove empty items
$c=$a.Count                     count items
$a|%{$y+=$_}                    sum
$b=$y/$c                        average
$a|%{$x+=(($_-$b)*($_-$b))/$c}  sum of squares/count
[math]::pow($x,0.5)             result
#>

result

:\>powershell -nologo -f stddev.ps1 45,67,32,98,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 45,  67,32,98,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 45,  67,32, 98 ,11,3
32.5303277300156

:\>powershell -nologo -f stddev.ps1 10035, 436844, 42463, 44774
175656.784413526

:\>powershell -nologo -f stddev.ps1 1,1,1,1,1,1
0

blabb

Posted 2015-10-15T17:11:46.067

Reputation: 219

0

Fortran, 138 bytes

Just a straightforward implementation of the equation in Fortran:

double precision function std(x)
integer,dimension(:),intent(in) :: x
std = norm2(dble(x-sum(x)/size(x)))/sqrt(dble(size(x)))
end function

Time Laird

Posted 2015-10-15T17:11:46.067

Reputation: 121