24
\$\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>

asked Oct 15, 2015 at 17:11
\$\endgroup\$
7
  • 1
    \$\begingroup\$ You mean the output must be a floating point OR integer? \$\endgroup\$ Commented Oct 15, 2015 at 18:01
  • 3
    \$\begingroup\$ I think most build-in standard deviation functions calculates the the sample standard deviation. \$\endgroup\$ Commented Oct 15, 2015 at 18:21
  • \$\begingroup\$ What about if input list is void?175656.78441352615 result to me 175656.78441352614 \$\endgroup\$ Commented Apr 24, 2017 at 19:16
  • 1
    \$\begingroup\$ @RosLuP You don't have to worry about that \$\endgroup\$ 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\$ Commented Dec 26, 2017 at 18:06

47 Answers 47

1
2
18
\$\begingroup\$

Clip, 3

.sk

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

answered Oct 15, 2015 at 18:00
\$\endgroup\$
6
  • \$\begingroup\$ What formula is used for the standard deviation? I could not find it int he reference. \$\endgroup\$ Commented Oct 15, 2015 at 18:11
  • \$\begingroup\$ @flawr It's this chart, towards the bottom. \$\endgroup\$ Commented Oct 15, 2015 at 18:13
  • 1
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I saw that, but there is no formula given. \$\endgroup\$ 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\$ Commented Oct 15, 2015 at 18:17
13
\$\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@#]&
answered Oct 15, 2015 at 20:57
\$\endgroup\$
0
11
\$\begingroup\$

Octave, 14 bytes

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

Try it on ideone.

answered Oct 15, 2015 at 17:55
\$\endgroup\$
1
  • 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\$ Commented Oct 20, 2015 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
answered Oct 16, 2015 at 3:20
\$\endgroup\$
8
\$\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.

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

Dyalog APL, (削除) 24 (削除ここまで) (削除) 23 (削除ここまで) (削除) 21 (削除ここまで) (削除) 20 (削除ここまで) (削除) 19 (削除ここまで) 17 bytes

×ばつM←+/÷≢

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

{.5*⍨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

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)

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

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

answered Oct 15, 2015 at 18:10
\$\endgroup\$
0
6
\$\begingroup\$

Julia 0.6, (削除) 26 (削除ここまで) 19 bytes

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

Try it online!

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
MarcMush
6,88515 silver badges18 bronze badges
answered Oct 15, 2015 at 19:35
\$\endgroup\$
5
\$\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\$
2
  • \$\begingroup\$ I agree with AndréMuta, this does not produce the required result, see here. \$\endgroup\$ 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\$ Commented Oct 15, 2015 at 18:29
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.
answered Oct 15, 2015 at 17:59
\$\endgroup\$
1
  • \$\begingroup\$ I like how the decomposition of a Pyth program looks like a skewed parabola. \$\endgroup\$ Commented Oct 19, 2015 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.
answered Oct 15, 2015 at 17:16
\$\endgroup\$
4
  • \$\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\$ 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\$ Commented Oct 16, 2015 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

answered Oct 15, 2015 at 18:47
\$\endgroup\$
1
  • \$\begingroup\$ Not every APL implementation supports {dfns}, , or . However, every version supports R←F Y R←(+/((Y-+/Y÷⍴Y)*2)÷⍴Y)*.5 \$\endgroup\$ Commented Dec 13, 2015 at 7:25
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.

answered Oct 15, 2015 at 18:27
\$\endgroup\$
2
  • \$\begingroup\$ You can use sum(1<$n) and <$> for map. \$\endgroup\$ 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\$ Commented Oct 30, 2017 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
answered Oct 15, 2015 at 18:16
\$\endgroup\$
5
  • \$\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\$ 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\$ Commented Oct 16, 2015 at 3:12
  • \$\begingroup\$ @xnor Edited. tbh I'm not really sure about the ruling on these situations... \$\endgroup\$ Commented Oct 16, 2015 at 3:30
  • \$\begingroup\$ Maybe a meta question would be helpful? :) \$\endgroup\$ Commented Oct 16, 2015 at 16:41
3
\$\begingroup\$

Haskell, 45 bytes

(?)i=sum.map(^i)
f l=sqrt2ドル?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.

answered Aug 24, 2020 at 7:18
\$\endgroup\$
3
\$\begingroup\$

Arn, (削除) 19 (削除ここまで) (削除) 18 (削除ここまで) 14 bytes

 ̄‡iʠØbmÅQƥaÈaÆ

Try it!

Explained

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

:/ Square root
 mean Mean function
 ( Begin expression
 n{ Block with key of n
 :* Square
 n
 - Subtraction
 mean
 _ Variable initialized to STDIN; implied
 :s Split on spaces
 } End of block
 \ Mapped over
 _ Implied
 ) End of expression; Implied
answered Aug 24, 2020 at 21:18
\$\endgroup\$
8
  • \$\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
3
\$\begingroup\$

Jelly

11 bytes

S÷L
Ç2_2ÇN1⁄2

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.
Ç2_2ÇN1⁄2 Main link. Argument: z (vector)
Ç Apply the previous link, i.e., compute the mean of z.
 2 Square the mean.
 2 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.
 1⁄2 Take the square root of the result.
emanresu A
46.2k5 gold badges111 silver badges257 bronze badges
answered Dec 12, 2015 at 21:36
\$\endgroup\$
3
\$\begingroup\$

☾, 20 characters (58 bytes)

しろまる󷺹ᴍ⬤2しろまる⬤-←⟞⨁÷🃌⟞→⨁÷🃌⟞

Try it: WASMoon online REPL

highlighted explanation

answered Mar 16 at 17:23
\$\endgroup\$
1
  • 2
    \$\begingroup\$ bro this taught me ⬤² and i made the lang what \$\endgroup\$ Commented Mar 16 at 18:25
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)
answered Oct 15, 2015 at 17:46
\$\endgroup\$
6
  • \$\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\$ Commented Oct 15, 2015 at 18:01
  • \$\begingroup\$ Yeah that's fine :) \$\endgroup\$ 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\$ Commented Oct 16, 2015 at 14:57
  • \$\begingroup\$ @StevenPenny It seems to work for me. \$\endgroup\$ Commented Aug 15, 2021 at 14:02
2
\$\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

answered Dec 1, 2015 at 12:12
\$\endgroup\$
2
\$\begingroup\$

J, 18 bytes

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

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

Try it online!

answered Dec 1, 2015 at 3:37
\$\endgroup\$
10
  • \$\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\$ 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\$ 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
2
\$\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
answered Apr 24, 2017 at 19:25
\$\endgroup\$
2
\$\begingroup\$

05AB1E, (削除) 10 (削除ここまで) 7 bytes

ÅA-nÅAt

-3 bytes thanks to @ovs.

Try it online or verify all test cases.

Explanation:

Å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)
answered Aug 24, 2020 at 8:48
\$\endgroup\$
1
  • 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\$ Commented Aug 24, 2020 at 10:05
2
\$\begingroup\$

Brachylog, 16 bytes

⟨∋-⟨+/l⟩⟩f^2m↰2√

Try it online! (all cases at once)

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

answered Aug 25, 2020 at 0:06
\$\endgroup\$
2
\$\begingroup\$

Uiua, 15 Characters

√-n2∩(/+÷⊸⧻)⤙n2

This takes advantage of the fact that $$\frac{1}{n}\sum_{i=1}^n(x_i-\mu)^2 = \frac{1}{n}\sum_{i=1}^n x_i^2 - 2\mu\frac{1}{n}\sum_{i=1}^nx_i+\mu^2 = \frac{1}{n}\sum_{i=1}^nx_i^2 - \mu^2.$$ Explanation:

√ # take a square root
 - # take the difference between top two numbers on stack
 n2 # square first entry of stack
 ∩ # apply the next function on top two items on stack
 (/+÷⊸⧻) # take average of a list of numbers
 ⤙n2 # square the top item on stack, but place result beneath the original list
answered Mar 16 at 21:46
\$\endgroup\$
2
\$\begingroup\$

Tcl, 90 bytes

proc S L {expr sqrt(([lmap x $L {list +($x-([join $L +])/[set n [llength $L]].)**2}])/$n)}

Try it online!


(削除) # [Tcl], 98 bytes
proc S L {expr sqrt(([join [lmap x $L {expr ($x-([join $L +])/[set n [llength $L]].)**2}] +])/$n)}

Try it online!

(削除ここまで)

answered Oct 22 at 21:15
\$\endgroup\$
1
  • \$\begingroup\$ Failed outgolf, 102: proc S L {expr sqrt((([join $L -([join $L +])/[set n [llength $L]].)**2+(]-([join $L +])/$n.)**2)/$n)}tio.run/… \$\endgroup\$ Commented Oct 22 at 23:32
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
answered Oct 16, 2015 at 6:00
\$\endgroup\$
1
\$\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
answered Oct 16, 2015 at 6:34
\$\endgroup\$
1
\$\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
Beta Decay
23.6k9 gold badges74 silver badges169 bronze badges
answered Oct 24, 2015 at 4:12
\$\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)
answered Oct 16, 2015 at 16:36
\$\endgroup\$
0
1
\$\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)
answered Jan 17, 2017 at 18:35
\$\endgroup\$
1
2

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.