[Python-Dev] Rounding float to int directly ...

Ron Adam rrr at ronadam.com
Tue Aug 1 23:07:57 CEST 2006


Nick Maclaren wrote:
> "M.-A. Lemburg" <mal at egenix.com> wrote:
>> You often have a need for controlled rounding when doing
>> financial calculations or in situations where you want to
>> compare two floats with a given accuracy, e.g. to work
>> around rounding problems ;-)
> 
> The latter is a crude hack, and was traditionally used to save cycles
> when floating-point division was very slow.  There are better ways,
> and have been for decades.
> 
>> Float formatting is an entirely different issue.
> 
> Not really.  You need controlled rounding to a fixed precision in
> the other base.  But I agree that controlled rounding in binary
> does not help with controlled rounding in decimal.


I'm -1 on implicitly converting to an int when rounding.

One reason is if your rounded (to int type) number is then used in an 
equation you my end up with a integer result when you wanted a floating 
point result.

 >>> 23.5/5.2
4.5192307692307692
 >>> round(23.5)/round(5.2)
4.7999999999999998
 >>> round(23.5/5.2)
5.0
 >>> int(round(23.5))/int(round(5.2))
4

Which one of these is correct probably depends on what you are using the 
  result for.  If it's an intermediate calculation you may not want an 
integer (type) result just yet.

Rounding is used in various differing ways in regard to significant 
digits and accuracy.  While it seems like there should be one easy way 
of handling rounding and significant digits, that would be too narrow a 
view.

See the following page (for starters) to see various uses and rules of 
significant digits and rounding and how they change depending on the 
type of calculation and weather or not its a pure or exact number:

     http://www.epcc.edu/faculty/victors/sigfig.htm



I think it's better to view that the common operation (being discussed) 
is rounding when converting to an int, and not converting to an int when 
rounding.  So the standard idiom mentioned earlier by Raymond ...

    int(x+.5)

If it could be made faster by having a round argument on int for such 
operations, it may be worth while.

   int(x, round=mode)

Where mode could be one of 'up','down','standard','toeven','toodd',  or 
whatever are useful methods that might be used.

If there is no performance advantage to combining the two, I think it 
would be better to keep them separate. So I'm -0 on giving the int 
constructor a rounding argument.

Just my 2 cents,
   Ron











More information about the Python-Dev mailing list