-1

I've got a reference value:

ref = 0.5

And a list:

my_list = [0.4, 0.5, 0.6, 0.5]

I'm trying to calculate how much, on average, the elements of my list differ from my reference value. Basically, it would be the same as a standard deviation, but instead of comparing with the mean of the list I'd like to compare with my reference value.

How could I do that the most efficiently in Python? Knowing that my lists are huge.

Notna
  • 491
  • 2
  • 8
  • 19
  • Your question is ambiguous. Do you want average distance or squared mean distance? Those aren't the same thing. – John Coleman Jul 31 '19 at 16:19
  • I'm looking for the root average of squared deviations of the variables in my list from the reference value - so as I said, just like a standard deviation – Notna Jul 31 '19 at 16:23

3 Answers3

1
import math
ref = 0.5
my_list = [0.4, 0.5, 0.6, 0.5]
std_ = math.sqrt( sum( [(x-ref)**2  for x in my_list] ) / len(my_list) )
Poojan
  • 3,366
  • 2
  • 17
  • 33
1

You could use numpy:

import numpy as np
my_list = [0.4, 0.5, 0.6, 0.5]
ref = 0.5

my_array = np.array(my_list)
sd = np.sqrt(np.mean((my_array - ref)**2))
print(sd) #prints 0.07071067811865474
John Coleman
  • 51,337
  • 7
  • 54
  • 119
  • And i think thats formula for `variance` not `std`. – Poojan Jul 31 '19 at 16:58
  • @Poojan [numpy](https://numpy.org/) is not one of the standard Python library modules, but has become part of the standard Python tool-chain for scientific computation. You need to install it (or use something like the Anaconda distribution that includes it). Also -- you were correct that I had neglected to take a square root at the end. Thanks. – John Coleman Jul 31 '19 at 16:58
0

For a lean approach use numpy with all it's possibilities:

import numpy as np

my_list = [0.4, 0.5, 0.6, 0.5]
ML = np.array(my_list)

myVal = 0.555

r1 = ML - myVal
r2 = np.sqrt(r1**2)
r3 = np.sum(r2)

print('r1:', r1)
print('r2:', r2)
print('r3:', r3)

r1: [-0.155 -0.055  0.045 -0.055]
r2: [0.155 0.055 0.045 0.055]
r3: 0.31000000000000005
pyano
  • 1,885
  • 10
  • 28