I have a problem where I am attempting to return the count of objects in an array that are within 1 standard deviation. In order to get standard deviation, I created two functions, but now I can't add/subtract the functions. I attempted to convert the functions to integers, but began getting an error regarding the fact that my standard deviation is a float. What is a better way to do all of this?
import numpy as np
import math
vac_nums=np.array([180, 172, 178, 185, 190, 195, 192, 200, 210, 190])
def variance():
n = len(vac_nums)
mean = sum(vac_nums)/n
deviations = [(x - mean) ** 2 for x in vac_nums]
variance = sum(deviations)/n
return variance
print(variance())
def stdev():
var = variance()
std_dev = math.sqrt(var)
return std_dev
print(stdev())
sum = 0
for x in vac_nums:
if np.array(x) >=(variance-stdev) and np.array(x) <=(variance stdev):
sum = 1
print(sum)
CodePudding user response:
Functions are first class objects in python, as are integers, lists, classes, and everything else you are likely to imagine on short notice. Functions can be called, in which case it returns a return value. A function is called with the ()
operator, sometimes containing arguments.
You've created two function objects in your code: variance
and stdev
. Those two names refer to the function objects.
You call the functions in each of the print
statements that follow them. For example variance()
is a call that returns a float
, which you can print.
The sum of two function objects is meaningless, as you would expect. You can add integers, floats, and even lists meaningfully, but what is the sum of functions? Since the return value of each of the functions is a number, you can add (or subtract) those meaningfully:
variance() stdev()
Normally we store the return value of an expensive function call to a variable once and use that variable instead of rerunning all the operations of the function. In python, you store variables by binding an object (like a return value) to a name using the =
operator. You could do something like this:
s = stdev()
print(s)
...
v = variance()
print(v)
...
# Use v s in an expression instead of variance stdev