#Original C version by R. G. Becker 1980
def vecRound(v, s, m):
	'''
	Given the list of numbers v,
	return a list, r, such that
	sum r[i] == s

	and r = m*v with a small number of deviations
	'''
	
	n = len(v)
	if not m: return (n*[0])[:]
	vs = 0
	r = []
	for i in v:
		ir = int(i*m+0.5)
		r.append(float(ir/m))
		vs += ir
	if vs==s: return r
	rincr = 1.0/m
	incr = 1
	if vs<s:
		xs = r
		rs = v
	else:
		xs = v
		rs = r
		incr = -incr
		rincr = -rincr

	while vs!=s:
		o = 10*abs(m)			# infinity
		for i in xrange(n):
			t = float(xs[i]-rs[i])
			if t<=o:
				if o==t:
					if abs(v[i])>abs(v[j]): j = i
				else:
					j = i
					o = t
		vs += incr
		r[j] += rincr
	return r

if __name__=='__main__':
	v=[9350,9350,9350,18700,39750,18700]
	import operator
	sum = float(reduce(operator.add,v))
	percen = map(lambda x,sum=sum: 100*x/sum, v)
	print v
	print percen
	print vecRound(percen,100,1)
	print vecRound(percen,100,10)
	print vecRound(percen,100,100)
