aleaxit / gmpy

General Multi-Precision arithmetic for Python 2.6+/3+ (GMP, MPIR, MPFR, MPC)
https://gmpy2.readthedocs.io/en/latest/
GNU Lesser General Public License v3.0
506 stars 84 forks source link

Executing advanced arithmetic operations --C++ to gmpy2 in Python #472

Open wanfuse123 opened 4 months ago

wanfuse123 commented 4 months ago

Hello,

I'm developing a project that necessitates seamless interaction between Python and C++, specifically for executing advanced arithmetic operations, including addition, subtraction, multiplication, division, exponentiation, and logarithms, on arbitrary precision numbers. I have chosen gmpy2 for its arbitrary precision capabilities in Python and am using PyBind11 to bind my C++ code to Python. Part of the project involves implementing root finding algorithms, where precision and speed is paramount along with python3's flexability for machine learning.

NOTE: Currently I am attempting to do this with PyBind11 but any solution that works is useful.

I have looked at ctypes as well, but dont find any good code examples, at a level I can understand, I seems this gap exists in existing libraries due to understandable complexity.

Environment:

OS: Debian 12 (bookworm) Python Version: 3.11.2 PyBind11 Version: (Please add your version here) gmpy2 Version: 2.1.5 GCC Version: (Debian 12.2.0-14) 12.2.0 The core of my query is about best practices for interfacing gmpy2's arbitrary precision numbers with C++ via PyBind11, especially for the operations mentioned. The challenges I'm facing include:

Efficiently passing gmpy2 arbitrary precision numbers from Python to C++ functions exposed via PyBind11. Conducting precise arithmetic and root finding calculations in C++ and ensuring that the precision of operations such as exponentiation and logarithms is maintained. Returning the results to Python without losing precision, ensuring the integrity of the numbers for further computations. I'm looking for guidance, examples, or references on how to effectively bridge gmpy2 and PyBind11 or boost.python or other built in method in gmpy2 for these purposes. Insights into handling high-precision arithmetic operations across Python and C++ would be invaluable.

Thank you for your assistance and expertise.

skirpichev commented 1 day ago

gmpy2 repo has demo/ directory with extension, that demonstrate using C API: it converts arguments to GMP's types, do factorization in C, using GMP functions, then converts result back to Python world. Probably you can do same, just use C++ wrapper for GMP.