1# Copyright 2017 The Chromium OS Authors. All rights reserved. 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4 5from math import ceil, floor, sqrt 6 7 8def get_kth_percentile(num_list, k): 9 """ 10 Computes the k-th percentile of a list of numbers. 11 12 @param num_list: list with numbers. 13 @param k: the percentile to be computed. 14 15 @returns the kth percentile value of the list. 16 17 """ 18 if not num_list: 19 return 0 20 assert k >= 0 and k <= 1 21 i = k * (len(num_list) - 1) 22 c, f = int(ceil(i)), int(floor(i)) 23 if c == f: 24 return num_list[c] 25 return round((i - f) * num_list[c] + (c - i) * num_list[f], 2) 26 27 28def get_median(num_list): 29 """ 30 Computes the median of a list of numbers. 31 32 @param num_list: a list with numbers. 33 34 @returns the median value of the numbers. 35 36 """ 37 if not num_list: 38 return 0 39 num_list.sort() 40 size = len(num_list) 41 if size % 2 != 0: 42 return num_list[size / 2] 43 return round((num_list[size / 2] + num_list[size / 2 - 1]) / 2.0, 2) 44 45 46def get_average(num_list): 47 """ 48 Computes mean of a list of numbers. 49 50 @param num_list: a list with numbers. 51 52 @returns the average value computed from the list of numbers. 53 54 """ 55 if not num_list: 56 return 0 57 return round(float(sum(num_list)) / len(num_list) , 2) 58 59 60def get_std_dev(num_list): 61 """ 62 Computes standard deviation of a list of numbers. 63 64 @param num_list: a list with numbers. 65 66 @returns Standard deviation computed from the list of numbers. 67 68 """ 69 n = len(num_list) 70 if not num_list or n == 1: 71 return 0 72 mean = float(sum(num_list)) / n 73 variance = sum([(elem - mean) ** 2 for elem in num_list]) / (n -1) 74 return round(sqrt(variance), 2)