[Python] sympy mod on formulas with custom functions

Discussão em 'Python' iniciado por Stack, Julho 14, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to define custom sympy functions which cannot be directly evaluated, but which I do want to be able to compute some things about. For example, modular remainders. Here's my code attempt:

    from sympy import Function

    class Foo(Function):
    @classmethod
    def eval(cls, n):
    pass

    def __mod__(self, modulus: int) -> int:
    n, = self.args
    return (n + 1) % modulus

    print(Foo(7) % 3)
    # 2
    print((Foo(7) + 1) % 3)
    # Mod(Foo(7) + 1, 3)
    print((Foo(7) + 1) % 3 == 0)
    # False


    So Foo(7) % 3 works as expected, but (Foo(7) + 1) % 3 does not, I wanted sympy to notice that it can compute (a + b) % 3 by computing a%3 and b%3. Is there some way to implement this? Perhaps I need to be more clever and write a new function that walks the symbolic tree of the formula? Or maybe I'm going about this the wrong way? I'm also open to other python libraries (I just guessed that sympy might be a good one to use).

    In case it helps, my real use-case for this is representing integers that are too large to store in memory and so can only be represented by formulas. But where we can still calculate some properties like modular remainders. See for example https://www.sligocki.com/2022/06/21/bb-6-2-t15.html

    Continue reading...

Compartilhe esta Página