gmpy icon indicating copy to clipboard operation
gmpy copied to clipboard

Support mixed-mode arithmetic rules for mpc & real types?

Open skirpichev opened this issue 1 year ago • 2 comments

The MPC has special routines to do arithmetic with operands of different types (i.e. mpc_t and mpfr_t), but gmpy2 don't use this stuff (for example, mpc_mul_fr()).

I think we should. Such arithmetic fix some analytical identities, that are broken in gmpy2 now. Consider asinh:

>>> import gmpy2
>>> z = gmpy2.mpc(-0.0, 2)
>>> gmpy2.asinh(z)
mpc('-1.3169578969248168+1.5707963267948966j')
>>> gmpy2.log(z + gmpy2.sqrt(1 + z*z))  # wrong real part, from other side of the branch cut
mpc('1.3169578969248166+1.5707963267948966j')

Also, I would expect some performance boost.

See also https://github.com/python/cpython/pull/124829

skirpichev avatar Oct 02 '24 05:10 skirpichev

This is a good idea. I've started work on it.

casevh avatar Oct 12 '24 05:10 casevh

Maybe it's wise to wait for a fate of above CPython PR. Note that special rules for real arguments can't save all identities, e.g. for atan: https://github.com/python/cpython/pull/124829#issuecomment-2387555557

Proper solution would be using also C99 Annex G imaginary-like type. But this one will be not closed under arithmetic operations (i.e. 1j*1j->-1.0). I'm thinking on a different approach (which might work for mpc too): https://github.com/python/cpython/pull/124829#discussion_r1788881051

skirpichev avatar Oct 12 '24 06:10 skirpichev

Ok, the CPython PR was merged and I'm working on this issue.

Probably, imaginary type (https://github.com/skirpichev/cpython/pull/1) will not be supported by Python. Anyway, the MPC has mixed-mode primitives only for real operands.

skirpichev avatar Jun 18 '25 14:06 skirpichev