[Numpy-discussion] A proposal for a round(x,n) enhancement

Christopher Smith csmith at blakeschool.org
Wed Sep 12 14:08:02 CDT 2001


Hello,

I would like to see an addition to the round(x,n) function syntax that
would allow 
one to specify that x should be rounded to the nth significant digit as
opposed to 
the nth digit to the left or right of the 1's digit.  I am testing the
waters right 
now on python-list and have not yet submitted a PEP.  

Some there have suggested that it be called a different function.  Someone
else has 
suggested that perhaps it could be added into SciPy or Numeric as a
function there.

I prefer the name round because it describes what you are doing.  Someone
suggested 
that MATLAB has a function called chop that does what I am proposing and at

http://www.math.colostate.edu/~tavener/M561/lab5/lab5.pdf

the document says that the "MATLAB function chop(x,n) rounds (not chops!)
the number 
x to n significant digits."  If this new function was called "chop" then
any previous 
MATLAB users would know what to expect.  (But why call it chop if you are
actually 
rounding?)  

What I think would be nice is to modify round so it can round to a given 
number of sig. figs.  Here is a def called Round that simulates what I am
proposing:


from math import floor,log10
def Round(x,n=0):
	if n%1:
		d=int(10*n)
		return round(x,d-1-int(floor(log10(abs(x)))))
	else:
		return round(x,n)
		
print Round(1.23456,2)   #returns 1.23
print Round(1.23456,0.2) #returns 1.2

The way that I have enhanced round's syntax is to have it check to see if
there is a 
non-zero decimal part to n.  If there is, n is multiplied by 10 and the
resulting 
value is used to compute which digit to round x to.  n=0.1 will round to
the first 
significant digit while n=0.4 and n=1.1 will round to the 4th and 11th,
respectively. 

I don't believe you will run into any numerical issues since even though
something 
like .3 may be represented internally as 0.29999999999999999, multiplying
it by 10 
gets you back to 3 and this value is what is used in the call to round()

I am open to comments about implementation and function name.

/c





More information about the Numpy-discussion mailing list