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

Use the following equation to calculate population standard deviation:


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


The numbers will always be integers.

Input will be to STDIN or function arguments.


The output must be a floating point number.


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

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


10035, 436844, 42463, 44774 => 175656.78441352615

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

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


The shortest program or function wins.


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>

  • 1
    \$\begingroup\$ You mean the output must be a floating point OR integer? \$\endgroup\$
    – Mutador
    Commented Oct 15, 2015 at 18:01
  • 3
    \$\begingroup\$ I think most build-in standard deviation functions calculates the the sample standard deviation. \$\endgroup\$
    – Mutador
    Commented Oct 15, 2015 at 18:21
  • \$\begingroup\$ What about if input list is void?175656.78441352615 result to me 175656.78441352614 \$\endgroup\$
    – user58988
    Commented Apr 24, 2017 at 19:16
  • \$\begingroup\$ @RosLuP You don't have to worry about that \$\endgroup\$
    – Beta Decay
    Commented Apr 24, 2017 at 19:29
  • 1
    \$\begingroup\$ @a13a22 As per PPCG's standard rules, you are fine to take input via function arguments \$\endgroup\$
    – Beta Decay
    Commented Dec 26, 2017 at 18:06

34 Answers 34


Clip, 3


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

  • \$\begingroup\$ What formula is used for the standard deviation? I could not find it int he reference. \$\endgroup\$
    – flawr
    Commented Oct 15, 2015 at 18:11
  • \$\begingroup\$ @flawr It's this chart, towards the bottom. \$\endgroup\$ Commented Oct 15, 2015 at 18:13
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I saw that, but there is no formula given. \$\endgroup\$
    – flawr
    Commented Oct 15, 2015 at 18:14
  • \$\begingroup\$ @flawr Oh, I see. Perhaps then it is up to the interpreter, if such a thing exists. \$\endgroup\$ Commented Oct 15, 2015 at 18:15
  • 2
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I found it here on line 493, it seems to be ok! \$\endgroup\$
    – flawr
    Commented Oct 15, 2015 at 18:17

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:


Yay. :)

This also works for 22 bytes:


And this for 27:


Octave, 14 bytes


Try it on ideone.

  • 2
    \$\begingroup\$ You can save two bytes by removing g= since the function handle doesn't need a name to be a valid submission. \$\endgroup\$
    – Alex A.
    Commented Oct 20, 2015 at 0:50

kdb+, 3 bytes


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

Test run

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

Dyalog APL, 24 23 21 20 19 17 bytes


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


Try them online on TryAPL.

How it works

The code consists of several trains.


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.


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


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).


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).


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.



R, 41 40 39 36 30 28 bytes


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


old codes


This should yield the population standard deviation.

  • 1
    \$\begingroup\$ I 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. \$\endgroup\$
    – beaker
    Commented Oct 15, 2015 at 18:45
  • 1
    \$\begingroup\$ On 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. \$\endgroup\$
    – Alex A.
    Commented Oct 15, 2015 at 18:57
  • 1
    \$\begingroup\$ Also, R uses ^ for exponentiation, which is a byte shorter than **. \$\endgroup\$
    – Alex A.
    Commented Oct 15, 2015 at 18:57
  • 1
    \$\begingroup\$ You 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) \$\endgroup\$
    – Alex A.
    Commented Oct 15, 2015 at 18:59
  • 1
    \$\begingroup\$ @AndréMuta apologies, when I tested it I had an X hanging around. \$\endgroup\$
    – MickyT
    Commented Oct 15, 2015 at 19:06

Julia, 26 19 bytes


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)])

Pyth, 20 19 17 13 bytes


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.
  • \$\begingroup\$ I like how the decomposition of a Pyth program looks like a skewed parabola. \$\endgroup\$ Commented Oct 19, 2015 at 14:51

CJam, 24 22 21 bytes


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.
  • \$\begingroup\$ I think you can convert just the length to double \$\endgroup\$ Commented Oct 15, 2015 at 20:01
  • \$\begingroup\$ @aditsu Of course. Thanks! \$\endgroup\$
    – Dennis
    Commented Oct 15, 2015 at 20:05
  • 5
    \$\begingroup\$ :mh is genius btw :) \$\endgroup\$ Commented Oct 15, 2015 at 20:06
  • 2
    \$\begingroup\$ Reduce by hypotenuse. isn't something you see every day. \$\endgroup\$
    – lirtosiast
    Commented Oct 16, 2015 at 3:48

APL, 24 bytes


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

  • \$\begingroup\$ Not every APL implementation supports {dfns}, , or . However, every version supports R←F Y R←(+/((Y-+/Y÷⍴Y)*2)÷⍴Y)*.5 \$\endgroup\$
    – Adám
    Commented Dec 13, 2015 at 7:25

TI-BASIC, 7 bytes


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:

  • \$\begingroup\$ I agree with AndréMuta, this does not produce the required result, see here. \$\endgroup\$
    – flawr
    Commented Oct 15, 2015 at 18:27
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – lirtosiast
    Commented Oct 15, 2015 at 18:29

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.

  • \$\begingroup\$ You can use sum(1<$n) and <$> for map. \$\endgroup\$
    – Laikoni
    Commented Oct 30, 2017 at 12:03
  • \$\begingroup\$ 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. \$\endgroup\$
    – Laikoni
    Commented Oct 30, 2017 at 12:07

Python 3.4+, 30 bytes

from statistics import*;pstdev

Imports the builtin function pstdev, e.g.

>>> pstdev([56,54,89,87])
  • \$\begingroup\$ 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, [...]) \$\endgroup\$ Commented Oct 15, 2015 at 18:52
  • \$\begingroup\$ I was going to say the same thing. Meta posts seem to support just putting a function literal. \$\endgroup\$
    – xnor
    Commented Oct 15, 2015 at 19:36
  • \$\begingroup\$ 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. \$\endgroup\$
    – xnor
    Commented Oct 16, 2015 at 3:12
  • \$\begingroup\$ @xnor Edited. tbh I'm not really sure about the ruling on these situations... \$\endgroup\$
    – Sp3000
    Commented Oct 16, 2015 at 3:30
  • \$\begingroup\$ Maybe a meta question would be helpful? :) \$\endgroup\$
    – Beta Decay
    Commented Oct 16, 2015 at 16:41


11 bytes


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.

Prolog (SWI), 119 bytes


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).


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


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

Try it out online here


J, 18 bytes


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

Try it online!

  • \$\begingroup\$ I had no idea M was a predefined built in. \$\endgroup\$ Commented Aug 6, 2016 at 4:31
  • \$\begingroup\$ It isn't. M=:+/%# is an inline function definition. \$\endgroup\$
    – Dennis
    Commented Aug 6, 2016 at 4:32
  • \$\begingroup\$ But it's predefined, right? Perhaps builtin is the wrong term \$\endgroup\$ Commented Aug 6, 2016 at 4:33
  • \$\begingroup\$ No, it's not predefined. M=:+/%# saves the verb +/%# in M, then calls it. \$\endgroup\$
    – Dennis
    Commented Aug 6, 2016 at 4:36
  • \$\begingroup\$ I am sorry XD I didn't see the last part \$\endgroup\$ Commented Aug 6, 2016 at 4:37

Haskell, 45 bytes

f l=sqrt$2?l/0?l-(1?l/0?l)^2

Try it online!

The value i?l is the sum of the i'th powers of elements in l, so that 0?l is the length and 1?l is the sum.


05AB1E, 10 7 bytes


-3 bytes thanks to @ovs.

Try it online or verify all test cases.


ÅA       # Get the arithmetic mean of the (implicit) input-list
  -      # Subtract it from each value in the (implicit) input-list
   n     # Square each of those
    ÅA   # Take the arithmetic mean of that
      t  # And take the square-root of that
         # (after which it is output implicitly as result)
  • 1
    \$\begingroup\$ Just found this challenge, ÅA-nÅAt is a more literal implementation of the given formula at 7 bytes. (This scores about 404 points in the other challenge) \$\endgroup\$
    – ovs
    Commented Aug 24, 2020 at 10:05

Brachylog, 16 bytes


Try it online! (all cases at once)

I feel like maybe there's some shorter way to compute the squared deviations than 13 bytes.


Arn, 19 18 14 bytes


Try it!


Unpacked: :/mean(n{:*n-mean:s}\

:/                      Square root
  mean                  Mean function
    (                   Begin expression
        n{              Block with key of n
          :*            Square
            -           Subtraction
                    _   Variable initialized to STDIN; implied
                  :s    Split on spaces
         }              End of block
       \                Mapped over
         _              Implied
    )                   End of expression; Implied
  • \$\begingroup\$ I'm very intrigued by Arn as a cool new different language. But am I getting it wrong or is the compression ('packing') quite inefficient? The 'unpacked' code is only 21 characters, including 2x the word 'mean' (which surely must be a single-byte token (?)) and 1x parenthesis (which could be completely avoided by rearranging to RPN), so I would have guessed that the 'packed' code would be at most 14 characters long. What am I missing? \$\endgroup\$ Commented Aug 27, 2020 at 18:28
  • \$\begingroup\$ Packing does not use that method of compression (mainly because most of the time you are NOT using a single word, but rather punctuation 90% of the time). Because of this, I essentially had two options for compression; pack the 7-bit characters into 8-bit characters (11% compression) or do something a bit stranger. The latter involves converting the ascii into a massive number (base 95) and then reading it off into a codepage, which results in approximately a 17% compression rate. Naturally, I chose option B here. That is why the compression doesn’t seem nearly as efficient as you thought. \$\endgroup\$ Commented Aug 27, 2020 at 19:09
  • \$\begingroup\$ Thanks for the explanation! It's particularly interesting to hear other languages' strategies now that there's a new 'golf a golfing language' challenge! Could you (or do you) at least reduce the text of 'mean' to 'M' (or 'ME' once you run-out of one-character function names) before doing the base95->256 compression, though? \$\endgroup\$ Commented Aug 28, 2020 at 6:27
  • \$\begingroup\$ I’ve considered shortening function names, but so far I haven’t. If a user wanted to shorten it manually, they could do this: m(_):=.mean \$\endgroup\$ Commented Aug 28, 2020 at 12:03
  • \$\begingroup\$ However, what you suggested is a good idea, and so I’ll test it out a bit \$\endgroup\$ Commented Aug 28, 2020 at 12:24

Simplex v.0.5, 43 bytes

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

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

JavaScript (ES6), 73 bytes

  • \$\begingroup\$ @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? \$\endgroup\$
    – Mwr247
    Commented Oct 15, 2015 at 18:01
  • \$\begingroup\$ Yeah that's fine :) \$\endgroup\$
    – Beta Decay
    Commented Oct 15, 2015 at 18:01
  • 7
    \$\begingroup\$ Psst... you can shave off 5 bytes by using this summing method eval(a.join`+`) instead of a.reduce((e,f)=>e+f) \$\endgroup\$ Commented Oct 15, 2015 at 22:31
  • \$\begingroup\$ @GeorgeReith Nice trick! I'm going to have to remember that one for later... \$\endgroup\$
    – Mwr247
    Commented Oct 16, 2015 at 14:57
  • \$\begingroup\$ @StevenPenny It seems to work for me. \$\endgroup\$ Commented Aug 15, 2021 at 14:02

Perl5, 39 38

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

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)

MathGolf, 10 7 bytes


Port of my 05AB1E answer.

Try it online.


ë        # Read all inputs as float-list
 _       # Duplicate that list
  ▓      # Get the average of that list
   -     # Subtract that average from each value in the list
    ²    # Square each value
     ▓   # Take the average of that again
      √  # And take the square root of that
         # (after which the entire stack joined together is output implicitly as result)

Whispers v2, 105 bytes

> Input
>> #1
>> ∑1
>> 3÷2
>> L-4
>> L²
>> Each 5 1
>> Each 6 7
>> ∑8
>> 9÷2
>> √10
>> Output 11

Try it online!

In the latest version of Whispers, the builtin σ can be used to shave off around 70 bytes.

How it works

For those unfamiliar with Whispers, the language works by using numbers as line references in order to pass values between lines. For example, the line >> 3÷2 doesn't calculate \$3 \div 2\$, rather it takes the values of lines 3 and 2 and calculates their division. Execution always begins on the last line.

This program simply implements the standard formula for standard deviation:

$$\sigma = \sqrt{\frac{1}{N}\sum^N_{i=1}{(x_i-\bar{x})^2}}$$ $$\bar{x} = \frac{1}{N}\sum^N_{i=1}{x_i}$$

Lines 2, 3 and 4 define \$\bar{x}\$, with it's specific value accessible on line 4. Line 2 stores \$N\$. We then calculate \$(x_i-\bar{x})^2\$ for each \$x_i \in x\$ with the lines 5, 6, 7 and 8:

>> L-4
>> L²
>> Each 5 1
>> Each 6 7

Line 7 runs line 5 over each element in the input, which takes the difference between each element in the input and the mean, We then square these differences using lines 8 and 6. Finally, we take the sum of these squares (line 9), divide by \$N\$ (line 10) and take the square root (line 11). Finally, we output this result.


Shasta v0.0.10, 65 bytes

{(**(/(sum(map${|x|(**(- x(/(sum$)(length$)))2)}))(length$)).5)}

Online interpreter not set up yet, tested on my machine


{...} Function taking argument $

(** ... .5) Square root of

(/ ... (length $)) Dividing ... by the length of $

(sum ...) The sum of

(map $ {|x| ...}) Mapping each x in $ to

(** ... 2) The square of

(- x ...) The difference between x and

(/ (sum $) (length $)) The mean of $


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

  • \$\begingroup\$ 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)? \$\endgroup\$
    – Alex A.
    Commented Oct 15, 2015 at 20:19
  • \$\begingroup\$ @AlexA. Uhh, no I don't think so... \$\endgroup\$
    – Beta Decay
    Commented Oct 15, 2015 at 20:30
  • 1
    \$\begingroup\$ Sorry, got confused. Disregard the x and l nonsense. But you can still do .5 to save a byte. \$\endgroup\$
    – Alex A.
    Commented Oct 15, 2015 at 20:31
  • 1
    \$\begingroup\$ @BetaDecay It's shorter to use a list-comp than to map a lambda: sum((x-sum(l)/len(l))**2for x in l). \$\endgroup\$
    – xnor
    Commented Oct 16, 2015 at 3:19
  • 1
    \$\begingroup\$ A different formulation gave the same length: lambda l:(sum(x*x*len(l)for x in l)-sum(l)**2)**.5/len(l). \$\endgroup\$
    – xnor
    Commented Oct 16, 2015 at 3:27

PowerShell, 122

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


$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


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

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

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

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

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

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

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.


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.


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
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

'calculate our popstdev
FOR I=0 TO N-1
PRINT SQR(1/N*T) 'sqrt(1/n*sum)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.