[Tutor] Re: Re: How to ignore some decimal values? (dman)

dman dsh8290@rit.edu
Thu, 17 Jan 2002 19:52:12 -0500


On Fri, Jan 18, 2002 at 12:25:04AM +0100, Ewald van Houte wrote:
| On Thu, 2002-01-17 at 10:47, dman wrote:	
| <snip>
| >
| >Ignoring the fact that binary floating point can't represent all
| >decimal numbers :
| >
| >def truncate( f , n ) :
| >    shift = 10**n
| >    return int( f*shift ) / shift
| >
| <snip>
| This doesn't give correct result:
| Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
| >>> print truncate(4.22,1)
| 4		#should be 4.2
| >>> print truncate(12.554,2)
| 12
| 
| division is int/int so result is int (with classic devision), but a
| float is needed. Small modification:

How about "from __future__ import division" ?  ;-).

>>> from __future__ import division
>>> def truncate( f , n ) :
>>> ...   shift = 10**n
>>> ...   return int( f*shift ) / shift
>>> ...
>>> truncate( 4.22 , 1 )
4.2000000000000002

(btw, you're right -- I didn't test it before)

(also you can see the limitations of binary fp above,
 print uses str() which rounds for you, the interactive interpreter
 uses repr() which shows all (or at least more) positions)

-D

-- 

One man gives freely, yet gains even more;
another withholds unduly, but comes to poverty.
        Proverbs 11:24