Truncated versus floored division in Python

2024/10/7 16:15:45

To establish context, I'm talking about integer arithmetic only, on large integers so going via floating point isn't an option, and using negative numbers so the difference between floored and truncated division matters.

When performing division on negative integers, typical hardware and C family programming languages give the truncated result e.g. 1 / -2 = 0. Python 2 gives the floored result e.g. 1 / -2 = -1.

Notwithstanding arguments about which is intrinsically better, is there a way to get Python to give the truncated result? Does it make any difference if you use Python 3 instead of 2?

Answer

Ok, if you just want a solution, remember int truncates the number, so instead of doing integer divison, truncate a float with int

int(1./-2)

If you are using Python 3.X, you can simply do

int(1/2)

If you want the same behavior in Py 2.X import division from future

from __future__ import division
int(1/2)

If you want to know the exact reason for this behavior, read this wonderful article Why Python's Integer Division Floors


Looking at your predicament in using float for division, here is an alternate approach that seems to be working as far as I have tested. Feel free to let me know of any issues you are facing

>>> def trunc_div(a,b):q, r = divmod(a,b)if  q < 0 and r:q += 1return q>>> trunc_div(1,-2)
0
>>> trunc_div(999999999999999999999999999999999999999999, -2)
-499999999999999999999999999999999999999999L
>>> trunc_div(999999999999999999999999999999999999999999, 2)
499999999999999999999999999999999999999999L
>>> trunc_div(1,2)
0
>>> 
https://en.xdnf.cn/q/70225.html

Related Q&A

when restoring from a checkpoint, how can I change the data type of the parameters?

I have a pre-trained Tensorflow checkpoint, where the parameters are all of float32 data type.How can I load checkpoint parameters as float16? Or is there a way to modify data types of a checkpoint?F…

Opencv Python open dng format

I cant figure out how to open a dng file in opencv. The file was created when using the pro options of the Samsung Galaxy S7. The images that are created when using those options are a dng file as well…

VSCode: Set environment variables via script

I have a shell script env.sh containing statements like export ENV_VAR1 = 1. On Linux terminal, I can use . env.sh or source env.sh to set the environment variables. How to set the environment variable…

TensorFlow performance bottleneck on IteratorGetNext

While fiddling around with TensorFlow, I noticed that a relatively simple task (batching some of our 3D accelerometer data and taking the sum of each epoch) was having relatively poor performance. Here…

SQLAlchemy - How to access column names from ResultProxy and write to CSV headers

I am trying to use SQLAlchemy to establish a connection to a PostgreSQL Database, execute a SQL query and print the output of the file to a file in linux. from sqlalchemy import create_engine import ya…

Python Facebook API - cursor pagination

My question involves learning how to retrieve my entire list of friends using Facebooks Python API. The current result returns an object with limited number of friends and a link to the next page. How …

PyQt Irregularly Shaped Windows (e.g. A circular without a border/decorations)

How do I create an irregularly shaped window in PyQt?I found this C++ solution, however I am unsure of how to do that in Python.

default values for variable argument list in Python

Is it possible to set a default value for a variable argument list in Python 3?Something like:def do_it(*args=(2, 5, 21)):passI wonder that a variable argument list is of type tuple but no tuple is ac…

Python error: execute cannot be used while an asynchronous query is underway

How do I prevent the error “ProgrammingError: execute cannot be used while an asynchronous query is underway”? From the docs it says that I should use psycopg2.extras.wait_select if I’m using a cor…

Clearing Django form fields on form validation error?

I have a Django form that allows a user to change their password. I find it confusing on form error for the fields to have the *ed out data still in them.Ive tried several methods for removing form.dat…