[Numpy-discussion] Rounding the decimal part of a real number

Christopher Barker Chris.Barker at noaa.gov
Wed Apr 6 12:06:00 EDT 2011


On 4/6/11 6:24 AM, Alan G Isaac wrote:
> http://docs.scipy.org/doc/numpy/reference/generated/numpy.round_.html

simple enough, of course, but just to be clear:

In [108]: np.round(1.23456789, 3)
Out[108]: 1.2350000000000001

so the number is rounded to the requested number of decimal places, but 
then stored in a binary floating point format, which may not be able to 
exactly represent that rounded number -- hence the "1" at the end. This 
is simply how floating point works.

and that slight difference _probably_ doesn't matter, but it's worth 
being aware of, because is does make a difference occasionally.

python has a decimal type that can work with exact decimal numbers -- 
numpy doesn't support that, as there is no hardware support for it (at 
least on most platforms).

If you want to display it differently, you can use the string formatters:

In [110]: "%.3f"%np.round(1.23456789, 3)
Out[110]: '1.235'

HTH, Chris


-- 
Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov



More information about the NumPy-Discussion mailing list