[Numpy-discussion] Re: PEP proposal for round(x,n) enhancement

Christopher Smith csmith at blakeschool.org
Sat Sep 15 13:28:01 CDT 2001


To Chris and others interested,

Would you mind giving me an opinion here?  I think you made the best
argument for not using the name "round" since floating n is already
accepted by round and changing how n is interpreted would break anyone's
code who passed in n with a non-zero decimal portion.  Sigfig or chop is
an alternative but I really don't like the name "chop" since it's not
descriptive of the rounding that takes place.  Sigfig is ok, but I am
proposing a round function (below) that offers more than just sigfigs. 
So...how about "round2" which has precedence in the atan2() function.  

The two sorts of roundings that can be done with round2() are 1) rounding
to a specified number of significant figures or 2) rounding to the nearest
"x".  The latter is useful if you are making a histogram, for example,
where experimental data values may all be distinct but when the deviation
of values is considered it makes sense to round the observations to a
specified uncertainty, e.g. if two values differ by less than sigma then
they could be considered to be part of the same "bin".

The script is below.

Thanks for any input,
/c

####
from math import floor,log10
def round2(x,n=0,sigs4n=1):
	'''Return x rounded to the specified number of significant digits, n, as
	counted from the first non-zero digit. 
	
	If n=0 (the default value for round2) then the magnitude of the
	number will be returned (e.g. round2(12) returns 10.0).  
	
	If n<0 then x will be rounded to the nearest multiple of n which, by 
	default, will be rounded to 1 digit (e.g. round2(1.23,-.28) will round 
	1.23 to the nearest multiple of 0.3.

	Regardless of n, if x=0, 0 will be returned.'''
	
	if x==0:
		return x
	if n<0:
		n=round2(-n,sigs4n)
		return n*int(x/n+.5)
	if n==0:
		return 10.**(int(floor(log10(abs(x)))))
	return round(x,int(n)-1-int(floor(log10(abs(x)))))
####





More information about the Numpy-discussion mailing list