Any way to do integer division in sympy?

2024/10/9 16:28:42

I have a very long expression that I think can be simplified, and I thought sympy would be the perfect way to do it. Unfortunately the formula relies on a couple of integer divides, and I can't find any way to represent those in sympy.

>>> x=Symbol('x')
>>> (x+1)/2
x/2 + 1/2

Clearly not what I want, 1/2 isn't an integer.

>>> (x+1)//2
TypeError: unsupported operand type(s) for //: 'Add' and 'int'

Obviously sympy doesn't handle //.

>>> Integer((x+1)/2)
#   A long list of error messages, ending with ...
TypeError: Integer can only work with integer expressions.

It seems that Integer is only intended to work on constant numbers, not formulas.

There's a function trunc but it doesn't seem to do anything similar to what I want.

Is there any way to represent an integer division in sympy?

Answer

Criteria

I assume that you want a function div that passes the following tests:

from sympy import sympify, simplify, Symboldef test_div(div):# check that div behaves as intended for integersfor i in range(-5,5):for j in range(-5,5):if j==0: continueassert i//j == div(sympify(i),sympify(j))# check that div’s output can be simplifiedx = Symbol("x", integer=True)assert simplify( div(x+1,2) - div(x-1,2) ) == 1

Modulo

You can realise an integer division using the modulo operator as follows:

div = lambda x,y: (x-x%y)/y

As SymPy supports modulo arithmetics and is capable of simplifying it, this function passes the above tests. However, if no full simplification is possible, you will end up with modulo expressions that may be undesired.

Floor

As already mentioned in the comments, SymPy provides a floor function, which could be used to acquire an integer division as (which is also how the // operator for expressions is implemented):

div = lambda x,y: sympy.floor(x/y)

However, floor does not support simplifications and therefore fails the second test.

https://en.xdnf.cn/q/70002.html

Related Q&A

Scrapy LinkExtractor - Limit the number of pages crawled per URL

I am trying to limit the number of crawled pages per URL in a CrawlSpider in Scrapy. I have a list of start_urls and I want to set a limit on the numbers pages are being crawled in each URL. Once the l…

Python Invalid format string [duplicate]

This question already has answers here:Python time formatting different in Windows(3 answers)Closed 9 years ago.I am trying to print the date in the following format using strftime: 06-03-2007 05:40PMI…

Python template safe substitution with the custom double-braces format

I am trying to substitute variables in the format {{var}} with Pythons Template. from string import Templateclass CustomTemplate(Template):delimiter = {{pattern = r\{\{(?:(?P<escaped>\{\{)|(?P…

Emit signal in standard python thread

I have a threaded application where I do have a network thread. The UI-part passes a callback to this thread. The thread is a normal python thread - its NO QThread.Is it possible to emit PyQT Slot with…

Sqlalchemy from_statement() cannot locate column

I am following the sqlalchemy tutorial in http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.htmlNevertheless, instead of using a SQLite backend, I am using MySQL. The problem is that when I try to exe…

Python - how to check if weak reference is still available

I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes...Is there any Python C/API a…

Django using locals() [duplicate]

This question already has answers here:Django template and the locals trick(8 answers)Closed 5 years ago.I am beginner in web development with Django. I have noticed that the locals() function is used …

python ghostscript: RuntimeError: Can not find Ghostscript library (libgs)

When trying to run hello-world exampleimport sys import ghostscriptargs = ["ps2pdf", # actual value doesnt matter"-dNOPAUSE", "-dBATCH", "-dSAFER","-sDEVICE…

what is the default encoding when python Requests post data is string type?

with fhe following codepayload = 工作报告 总体情况:良好 r = requests.post("http://httpbin.org/post", data=payload)what is the default encoding when Requests post data is string type? UTF8…

How to initialize a database connection only once and reuse it in run-time in python?

I am currently working on a huge project, which constantly executes queries. My problem is, that my old code always created a new database connection and cursor, which decreased the speed immensivly. S…