Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #101966
| From | Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: How to simulate C style integer division? |
| Date | 2016-01-21 15:22 +0100 |
| Message-ID | <mailman.149.1453386144.15297.python-list@python.org> (permalink) |
| References | <CAJQX3DyoDUtNWbNEpGVJxeKATADWAikP47NRZb7+UaxSwSRZaQ@mail.gmail.com> <mailman.143.1453367498.15297.python-list@python.org> <56a0d24f$0$1614$c3e8da3$5496439d@news.astraweb.com> <lf5mvrzuj5z.fsf@ling.helsinki.fi> |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: How to simulate C style integer division? Ben Finney <ben+python@benfinney.id.au> - 2016-01-21 20:11 +1100
Re: How to simulate C style integer division? Paul Rubin <no.email@nospam.invalid> - 2016-01-21 01:43 -0800
Re: How to simulate C style integer division? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-01-21 11:58 +0200
Re: How to simulate C style integer division? Steven D'Aprano <steve@pearwood.info> - 2016-01-21 23:42 +1100
Re: How to simulate C style integer division? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-01-21 16:00 +0200
Re: How to simulate C style integer division? Marko Rauhamaa <marko@pacujo.net> - 2016-01-21 16:31 +0200
Re: How to simulate C style integer division? Jussi Piitulainen <jussi.piitulainen@helsinki.fi> - 2016-01-21 16:48 +0200
Re: How to simulate C style integer division? Random832 <random832@fastmail.com> - 2016-01-21 14:52 -0500
Re: How to simulate C style integer division? Marko Rauhamaa <marko@pacujo.net> - 2016-01-21 23:17 +0200
Re: How to simulate C style integer division? Matt Wheeler <m@funkyhat.org> - 2016-01-22 00:51 +0000
Re: How to simulate C style integer division? Wolfgang Maier <wolfgang.maier@biologie.uni-freiburg.de> - 2016-01-21 15:22 +0100
csiph-web