Calculating population standard deviationCalculating Standard Deviation using SQLPythonic sieve of...
If I receive an SOS signal, what is the proper response?
Why would one plane in this picture not have gear down yet?
Is it possible to avoid unpacking when merging Association?
Why does the negative sign arise in this thermodynamic relation?
Error during using callback start_page_number in lualatex
NASA's RS-25 Engines shut down time
What problems would a superhuman have whose skin is constantly hot?
Accountant/ lawyer will not return my call
Does "Until when" sound natural for native speakers?
How do I express some one as a black person?
Does the nature of the Apocalypse in The Umbrella Academy change from the first to the last episode?
Are there historical instances of the capital of a colonising country being temporarily or permanently shifted to one of its colonies?
Recommendation letter by significant other if you worked with them professionally?
Counting all the hearts
Reverse string, can I make it faster?
Bash script should only kill those instances of another script's that it has launched
What wound would be of little consequence to a biped but terrible for a quadruped?
Why does liquid water form when we exhale on a mirror?
Signed and unsigned numbers
Doesn't allowing a user mode program to access kernel space memory and execute the IN and OUT instructions defeat the purpose of having CPU modes?
Word for a person who has no opinion about whether god exists
PTIJ: wiping amalek’s memory?
What's the "normal" opposite of flautando?
How is the wildcard * interpreted as a command?
Calculating population standard deviation
Calculating Standard Deviation using SQLPythonic sieve of Erasthotones that saves results to fileStatistics with PythonMultiple files data processing in ClojureJSON file for storing means and standard deviation values per demographic groupsegment tree for adding a array with single index updatesEstimating the number of tanks based on a sample of serial numbers 2.0Compute mean, variance and standard deviation of CSV number fileCompute mean and variance, incrementallyPython program computing some statistics on Scottish geographic areas
$begingroup$
This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic.
from math import sqrt
def mean(lst):
"""calculates mean"""
sum = 0
for i in range(len(lst)):
sum += lst[i]
return (sum / len(lst))
def stddev(lst):
"""calculates standard deviation"""
sum = 0
mn = mean(lst)
for i in range(len(lst)):
sum += pow((lst[i]-mn),2)
return sqrt(sum/len(lst)-1)
numbers = [120,112,131,211,312,90]
print stddev(numbers)
python statistics
$endgroup$
add a comment |
$begingroup$
This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic.
from math import sqrt
def mean(lst):
"""calculates mean"""
sum = 0
for i in range(len(lst)):
sum += lst[i]
return (sum / len(lst))
def stddev(lst):
"""calculates standard deviation"""
sum = 0
mn = mean(lst)
for i in range(len(lst)):
sum += pow((lst[i]-mn),2)
return sqrt(sum/len(lst)-1)
numbers = [120,112,131,211,312,90]
print stddev(numbers)
python statistics
$endgroup$
add a comment |
$begingroup$
This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic.
from math import sqrt
def mean(lst):
"""calculates mean"""
sum = 0
for i in range(len(lst)):
sum += lst[i]
return (sum / len(lst))
def stddev(lst):
"""calculates standard deviation"""
sum = 0
mn = mean(lst)
for i in range(len(lst)):
sum += pow((lst[i]-mn),2)
return sqrt(sum/len(lst)-1)
numbers = [120,112,131,211,312,90]
print stddev(numbers)
python statistics
$endgroup$
This is a script I have written to calculate the population standard deviation. I feel that this can be simplified and also be made more pythonic.
from math import sqrt
def mean(lst):
"""calculates mean"""
sum = 0
for i in range(len(lst)):
sum += lst[i]
return (sum / len(lst))
def stddev(lst):
"""calculates standard deviation"""
sum = 0
mn = mean(lst)
for i in range(len(lst)):
sum += pow((lst[i]-mn),2)
return sqrt(sum/len(lst)-1)
numbers = [120,112,131,211,312,90]
print stddev(numbers)
python statistics
python statistics
edited Aug 24 '14 at 16:25
Jamal♦
30.4k11121227
30.4k11121227
asked Feb 21 '12 at 11:03
AnimeshAnimesh
2492613
2492613
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
$begingroup$
The easiest way to make mean()
more pythonic is to use the sum()
built-in function.
def mean(lst):
return sum(lst) / len(lst)
Concerning your loops on lists, you don't need to use range()
. This is enough:
for e in lst:
sum += e
Other comments:
- You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
- Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
- Why do you use "-1" in the return for stddev? Is that a bug?
- You are computing the standard deviation using the variance: call that "variance", not sum!
- You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
- You shouldn't use pow() anyway, ** is enough.
This would give:
def stddev(lst):
"""returns the standard deviation of lst"""
variance = 0
mn = mean(lst)
for e in lst:
variance += (e-mn)**2
variance /= len(lst)
return sqrt(variance)
It's still way too verbose! Since we're handling lists, why not using list comprehensions?
def stddev(lst):
"""returns the standard deviation of lst"""
mn = mean(lst)
variance = sum([(e-mn)**2 for e in lst]) / len(lst)
return sqrt(variance)
This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.
$endgroup$
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
|
show 1 more comment
$begingroup$
You have some serious calculation errors…
Assuming that this is Python 2, you also have bugs in the use of division: if both operands of /
are integers, then Python 2 performs integer division. Possible remedies are:
from __future__ import division
- Cast one of the operands to a
float
:return (float(sum)) / len(lst)
, for example.
(Assuming that this is Python 3, you can just use statistics.stdev()
.
The formula for the sample standard deviation is
$$ s = sqrt{frac{sum_{i=1}^{n} (x_i - bar{x})^2}{n - 1}}$$
In return sqrt(sum/len(lst)-1)
, you have an error with the precedence of operations. It should be
return sqrt(float(sum) / (len(lst) - 1))
$endgroup$
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
add a comment |
$begingroup$
Does not work, Example:
import scipy.stats as ss
import numpy as np
x = np.arange(-5,5,0.01) # X AXIS VALUES
y = ss.norm(0.0, 1.0).pdf(x) #Generate Normally Distributed values mu = 0.0, sigma = 1.0
print("The Std. Dev. of y =", np.std(y))
Result =
The Std. Dev. of y = 0.13494254572180692 #Shoud be approx = 1.0 by definition of y
New contributor
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f9222%2fcalculating-population-standard-deviation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
The easiest way to make mean()
more pythonic is to use the sum()
built-in function.
def mean(lst):
return sum(lst) / len(lst)
Concerning your loops on lists, you don't need to use range()
. This is enough:
for e in lst:
sum += e
Other comments:
- You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
- Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
- Why do you use "-1" in the return for stddev? Is that a bug?
- You are computing the standard deviation using the variance: call that "variance", not sum!
- You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
- You shouldn't use pow() anyway, ** is enough.
This would give:
def stddev(lst):
"""returns the standard deviation of lst"""
variance = 0
mn = mean(lst)
for e in lst:
variance += (e-mn)**2
variance /= len(lst)
return sqrt(variance)
It's still way too verbose! Since we're handling lists, why not using list comprehensions?
def stddev(lst):
"""returns the standard deviation of lst"""
mn = mean(lst)
variance = sum([(e-mn)**2 for e in lst]) / len(lst)
return sqrt(variance)
This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.
$endgroup$
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
|
show 1 more comment
$begingroup$
The easiest way to make mean()
more pythonic is to use the sum()
built-in function.
def mean(lst):
return sum(lst) / len(lst)
Concerning your loops on lists, you don't need to use range()
. This is enough:
for e in lst:
sum += e
Other comments:
- You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
- Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
- Why do you use "-1" in the return for stddev? Is that a bug?
- You are computing the standard deviation using the variance: call that "variance", not sum!
- You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
- You shouldn't use pow() anyway, ** is enough.
This would give:
def stddev(lst):
"""returns the standard deviation of lst"""
variance = 0
mn = mean(lst)
for e in lst:
variance += (e-mn)**2
variance /= len(lst)
return sqrt(variance)
It's still way too verbose! Since we're handling lists, why not using list comprehensions?
def stddev(lst):
"""returns the standard deviation of lst"""
mn = mean(lst)
variance = sum([(e-mn)**2 for e in lst]) / len(lst)
return sqrt(variance)
This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.
$endgroup$
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
|
show 1 more comment
$begingroup$
The easiest way to make mean()
more pythonic is to use the sum()
built-in function.
def mean(lst):
return sum(lst) / len(lst)
Concerning your loops on lists, you don't need to use range()
. This is enough:
for e in lst:
sum += e
Other comments:
- You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
- Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
- Why do you use "-1" in the return for stddev? Is that a bug?
- You are computing the standard deviation using the variance: call that "variance", not sum!
- You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
- You shouldn't use pow() anyway, ** is enough.
This would give:
def stddev(lst):
"""returns the standard deviation of lst"""
variance = 0
mn = mean(lst)
for e in lst:
variance += (e-mn)**2
variance /= len(lst)
return sqrt(variance)
It's still way too verbose! Since we're handling lists, why not using list comprehensions?
def stddev(lst):
"""returns the standard deviation of lst"""
mn = mean(lst)
variance = sum([(e-mn)**2 for e in lst]) / len(lst)
return sqrt(variance)
This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.
$endgroup$
The easiest way to make mean()
more pythonic is to use the sum()
built-in function.
def mean(lst):
return sum(lst) / len(lst)
Concerning your loops on lists, you don't need to use range()
. This is enough:
for e in lst:
sum += e
Other comments:
- You don't need parentheses around the return value (check out PEP 8 when you have a doubt about this).
- Your docstrings are useless: it's obvious from the name that it calculates the mean. At least make them more informative ("returns the mean of lst").
- Why do you use "-1" in the return for stddev? Is that a bug?
- You are computing the standard deviation using the variance: call that "variance", not sum!
- You should type pow(e-mn,2), not pow((e-mn),2). Using parentheses inside a function call could make the reader think he's reading a tuple (eg. pow((e,mn),2) is valid syntax)
- You shouldn't use pow() anyway, ** is enough.
This would give:
def stddev(lst):
"""returns the standard deviation of lst"""
variance = 0
mn = mean(lst)
for e in lst:
variance += (e-mn)**2
variance /= len(lst)
return sqrt(variance)
It's still way too verbose! Since we're handling lists, why not using list comprehensions?
def stddev(lst):
"""returns the standard deviation of lst"""
mn = mean(lst)
variance = sum([(e-mn)**2 for e in lst]) / len(lst)
return sqrt(variance)
This is not perfect. You could add tests using doctest. Obviously, you should not code those functions yourself, except in a small project. Consider using Numpy for a bigger project.
edited Sep 11 '17 at 5:11
answered Feb 21 '12 at 13:01
Quentin PradetQuentin Pradet
6,59611843
6,59611843
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
|
show 1 more comment
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
Thank you Cygal for your answer. I realize things like tests and validation need to be added, but I think you put me in the right direction.
$endgroup$
– Animesh
Feb 22 '12 at 8:23
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
@mad, I realize you're not able to comment due to your reputation, but if you see a problem in a post and want to fix it, you'll either have to be patient and wait until you have 50 reputation or go out, answer a question, and get five upvotes (or ask a good question and get 10). Please don't try to circumvent the system. Third-party edits should only edit the content of the post (as opposed to formatting, grammar, spelling, pasting in content from links etc.) with explicit approval from the poster.
$endgroup$
– Nic Hartley
Dec 30 '15 at 20:09
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
Looks like you forgot to divide the variance by N before taking the sqrt in the last/least verbose example.
$endgroup$
– Cody A. Ray
Sep 29 '16 at 16:41
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@CodyA.Ray Your Rev 2 corrected the result, but it was not the right fix.
$endgroup$
– 200_success
Sep 29 '16 at 19:19
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
$begingroup$
@200_success can you elaborate? Yeah, variance is the wrong variable name there. I could've just divided in the "return" line. But the equation seems correct for non-sampled std dev: libweb.surrey.ac.uk/library/skills/Number%20Skills%20Leicester/…
$endgroup$
– Cody A. Ray
Sep 29 '16 at 22:09
|
show 1 more comment
$begingroup$
You have some serious calculation errors…
Assuming that this is Python 2, you also have bugs in the use of division: if both operands of /
are integers, then Python 2 performs integer division. Possible remedies are:
from __future__ import division
- Cast one of the operands to a
float
:return (float(sum)) / len(lst)
, for example.
(Assuming that this is Python 3, you can just use statistics.stdev()
.
The formula for the sample standard deviation is
$$ s = sqrt{frac{sum_{i=1}^{n} (x_i - bar{x})^2}{n - 1}}$$
In return sqrt(sum/len(lst)-1)
, you have an error with the precedence of operations. It should be
return sqrt(float(sum) / (len(lst) - 1))
$endgroup$
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
add a comment |
$begingroup$
You have some serious calculation errors…
Assuming that this is Python 2, you also have bugs in the use of division: if both operands of /
are integers, then Python 2 performs integer division. Possible remedies are:
from __future__ import division
- Cast one of the operands to a
float
:return (float(sum)) / len(lst)
, for example.
(Assuming that this is Python 3, you can just use statistics.stdev()
.
The formula for the sample standard deviation is
$$ s = sqrt{frac{sum_{i=1}^{n} (x_i - bar{x})^2}{n - 1}}$$
In return sqrt(sum/len(lst)-1)
, you have an error with the precedence of operations. It should be
return sqrt(float(sum) / (len(lst) - 1))
$endgroup$
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
add a comment |
$begingroup$
You have some serious calculation errors…
Assuming that this is Python 2, you also have bugs in the use of division: if both operands of /
are integers, then Python 2 performs integer division. Possible remedies are:
from __future__ import division
- Cast one of the operands to a
float
:return (float(sum)) / len(lst)
, for example.
(Assuming that this is Python 3, you can just use statistics.stdev()
.
The formula for the sample standard deviation is
$$ s = sqrt{frac{sum_{i=1}^{n} (x_i - bar{x})^2}{n - 1}}$$
In return sqrt(sum/len(lst)-1)
, you have an error with the precedence of operations. It should be
return sqrt(float(sum) / (len(lst) - 1))
$endgroup$
You have some serious calculation errors…
Assuming that this is Python 2, you also have bugs in the use of division: if both operands of /
are integers, then Python 2 performs integer division. Possible remedies are:
from __future__ import division
- Cast one of the operands to a
float
:return (float(sum)) / len(lst)
, for example.
(Assuming that this is Python 3, you can just use statistics.stdev()
.
The formula for the sample standard deviation is
$$ s = sqrt{frac{sum_{i=1}^{n} (x_i - bar{x})^2}{n - 1}}$$
In return sqrt(sum/len(lst)-1)
, you have an error with the precedence of operations. It should be
return sqrt(float(sum) / (len(lst) - 1))
answered Aug 24 '14 at 16:56
200_success200_success
130k16153419
130k16153419
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
add a comment |
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
Source for formula?
$endgroup$
– Agostino
Mar 26 '15 at 23:40
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
$begingroup$
@Agostino It's basically common knowledge in statistics.
$endgroup$
– 200_success
Mar 26 '15 at 23:42
add a comment |
$begingroup$
Does not work, Example:
import scipy.stats as ss
import numpy as np
x = np.arange(-5,5,0.01) # X AXIS VALUES
y = ss.norm(0.0, 1.0).pdf(x) #Generate Normally Distributed values mu = 0.0, sigma = 1.0
print("The Std. Dev. of y =", np.std(y))
Result =
The Std. Dev. of y = 0.13494254572180692 #Shoud be approx = 1.0 by definition of y
New contributor
$endgroup$
add a comment |
$begingroup$
Does not work, Example:
import scipy.stats as ss
import numpy as np
x = np.arange(-5,5,0.01) # X AXIS VALUES
y = ss.norm(0.0, 1.0).pdf(x) #Generate Normally Distributed values mu = 0.0, sigma = 1.0
print("The Std. Dev. of y =", np.std(y))
Result =
The Std. Dev. of y = 0.13494254572180692 #Shoud be approx = 1.0 by definition of y
New contributor
$endgroup$
add a comment |
$begingroup$
Does not work, Example:
import scipy.stats as ss
import numpy as np
x = np.arange(-5,5,0.01) # X AXIS VALUES
y = ss.norm(0.0, 1.0).pdf(x) #Generate Normally Distributed values mu = 0.0, sigma = 1.0
print("The Std. Dev. of y =", np.std(y))
Result =
The Std. Dev. of y = 0.13494254572180692 #Shoud be approx = 1.0 by definition of y
New contributor
$endgroup$
Does not work, Example:
import scipy.stats as ss
import numpy as np
x = np.arange(-5,5,0.01) # X AXIS VALUES
y = ss.norm(0.0, 1.0).pdf(x) #Generate Normally Distributed values mu = 0.0, sigma = 1.0
print("The Std. Dev. of y =", np.std(y))
Result =
The Std. Dev. of y = 0.13494254572180692 #Shoud be approx = 1.0 by definition of y
New contributor
New contributor
answered 8 mins ago
VadulamVadulam
1
1
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f9222%2fcalculating-population-standard-deviation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown