Path: csiph.com!news.swapon.de!fu-berlin.de!uni-berlin.de!not-for-mail From: Wolfgang Maier Newsgroups: comp.lang.python Subject: Re: How to simulate C style integer division? Date: Thu, 21 Jan 2016 15:22:12 +0100 Lines: 35 Message-ID: References: <56a0d24f$0$1614$c3e8da3$5496439d@news.astraweb.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de ILhdzfTDgzoNgZv2DK6FkwPtIypWlFVvIbKnngc0lOQA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'merging': 0.07; 'subject:How': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'zero.': 0.09; 'def': 0.13; '0):': 0.16; 'b):': 0.16; 'increment': 0.16; 'received:80.91.229.3': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'truncation': 0.16; 'wrote:': 0.16; 'integer': 0.18; 'cheers,': 0.22; 'header:In-Reply-To:1': 0.24; 'software.': 0.25; 'header:User-Agent:1': 0.26; 'header:X -Complaints-To:1': 0.26; 'right.': 0.27; '---': 0.28; 'towards': 0.28; 'be:': 0.29; 'behaviour': 0.29; 'division': 0.29; 'received:132': 0.29; 'certainly': 0.30; 'checked': 0.31; 'guess': 0.31; "d'aprano": 0.33; 'steven': 0.33; 'should': 0.36; 'there': 0.36; 'to:addr:python-list': 0.36; 'subject:?': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'suggestion': 0.37; 'to:addr:python.org': 0.40; 'antivirus': 0.66; 'avast': 0.84; 'obvious,': 0.91 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: 132.230.194.220 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Thunderbird/38.5.0 In-Reply-To: X-Antivirus: avast! (VPS 160121-0, 01/21/2016), Outbound message X-Antivirus-Status: Clean X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:101966 On 1/21/2016 15:00, Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> So my guess is that the fastest, and certainly the most obvious, way >> to get the same integer division behaviour as C99 would be: >> >> def intdiv(a, b): >> # C99 style integer division with truncation towards zero. >> n = a//b >> if (a < 0) != (b < 0): >> n += 1 >> return n > > You should only increment if there is a (non-zero) remainder. > Right. Merging Steven's suggestion and fractions.Fraction.__trunc__ implementation I think the right answer may be: def intdiv2(a,b): # C99 style integer division with truncation towards zero. if (a < 0) != (b < 0): return -(-a // b) else: return a // b Cheers, Wolfgang --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus