19
\$\begingroup\$

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>

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

26 Answers 26

18
\$\begingroup\$

Clip, 3

.sk

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

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

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@#]&
\$\endgroup\$
10
\$\begingroup\$

Octave, 14 bytes

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

Try it on ideone.

\$\endgroup\$
  • 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. Oct 20 '15 at 0:50
10
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
5
\$\begingroup\$

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.

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

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.
\$\endgroup\$
  • \$\begingroup\$ I like how the decomposition of a Pyth program looks like a skewed parabola. \$\endgroup\$ – Conor O'Brien Oct 19 '15 at 14:51
5
\$\begingroup\$

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

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

\$\endgroup\$
  • \$\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 Dec 13 '15 at 7:25
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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

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.

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

Python 3.4+, 30 bytes

from statistics import*;pstdev

Imports the builtin function pstdev, e.g.

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

JavaScript (ES6), 73 bytes

a=>Math.sqrt(a.reduce((b,c)=>b+(d=c-eval(a.join`+`)/(l=a.length))*d,0)/l)
\$\endgroup\$
  • \$\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 Oct 15 '15 at 18:01
  • \$\begingroup\$ Yeah that's fine :) \$\endgroup\$ – Beta Decay Oct 15 '15 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\$ – George Reith Oct 15 '15 at 22:31
  • \$\begingroup\$ @GeorgeReith Nice trick! I'm going to have to remember that one for later... \$\endgroup\$ – Mwr247 Oct 16 '15 at 14:57
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

J, 18 bytes

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

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

Try it online!

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

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
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\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. Oct 15 '15 at 20:19
  • \$\begingroup\$ @AlexA. Uhh, no I don't think so... \$\endgroup\$ – Beta Decay Oct 15 '15 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. Oct 15 '15 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 Oct 16 '15 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 Oct 16 '15 at 3:27
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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)
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Pyt, 13 bytes

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

Implements the formula for standard deviation

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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