开发者

Conditional for negative integer

I'm defining a function that calculates the standard deviation of a list. Sometimes the mean of t开发者_如何学运维his list is negative and so my function can't take the square root of a negative, returning me with an error.

This seems simple, I just can't think of it. I want to write a conditional for my function saying that if there is a negative number, to multiply by -1 since the square root of a negative number cannot be taken.

How can I write this statement?

def stdevValue(lst):
"""calculates the standard deviation of a list of numbers
input: list of numbers
output: float that is the standard deviation
"""
    stdev = 0
    stdevCalc = (((sum(lst) - (meanValue(x)))/(len(lst)-1)))**0.5
    stdev += stdevCalc
    return stdev


You appear to have misapplied the formula for standard deviation. You shouldn't need to handle the case of square root of negative numbers at all. You need to square each difference between the value and the mean before summing, like this:

def stdevValue(lst):
    m = meanValue(x) # wherever this comes from
    return (sum((x - m) ** 2 for x in lst) / len(lst)) ** 0.5

This ensures that the sum is nonnegative, so you can take the square root without being concerned about negative values. (If you want sample standard deviation, divide by (len(lst) - 1)).

See the Wikipedia article on Standard Deviation for more information and examples.


Ignoring the context of the question, the answer is to use the built-in abs. But if you have a mathematical expression of type y = sqrt(x), and y cannot be complex, then x cannot be negative. Any negative x denotes a problem, which could be rounding, wrapping, or, as in your case, an incorrect formula. Simply multiplying by -1, or taking the abs, will not fix the problem, it will give you the wrong answer. You should maybe consider how to deal with these cases (although I appreciate that for the case of standard deviation these errors are unlikely to arise).


If you want to really get creative, you can square and square-root:

>>> import math
>>> x = -5
>>> math.sqrt((-5)**2)
5.0

Cheers

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜