import math


def slidingStandardDeviationCalc(avg, var, x_0, x_n, windowSize):
	"""
	Return the variance and standard deviation based on the previous variance.

	:param avg: The average value of the items in the window x[0]..x[n-1]
	:param var: The variance of the items in the window x[0]..x[n-1]
	:param x_0: The item of the window to be counted out of the rolling 
				standard deviation
	:param x_n: The item of the window to be counted into the rolling standard 
				deviation
	:param windowSize: The number of items in the calculation.
	:returns: newVar: The new variance, ie. of x[1]..x[n]; and newStdDev: The
			  new standard deviation of same, ie. sqrt(newVar)
	"""

	newAvg = avg + (x_n - x_0) / windowSize
	newVar = var + (x_n - newAvg + x_0 - avg) * (x_n - x_0) / (windowSize - 1)
	# I've read that very small values can give a slightly negative std. dev. 
	# due to floating point arithmetic, leading to a negative square root.
	# Thus, we round it to 0. Not ideal but it prevents a crash case.
	if newVar < 0:
		newVar = 0

	newStdDev = math.sqrt(newVar)
	return newVar, newStdDev