Skip to content

mpmath.mp.mpf has outdated __float__ dunder #38223

@skirpichev

Description

@skirpichev

One looks like:

def __float__(self):
"""
Support float conversion for derived classes ::
sage: from mpmath import mpf
sage: from sage.libs.mpmath.ext_main import mpf_base
sage: class X(mpf_base): _mpf_ = mpf(3.25)._mpf_
sage: float(X())
3.25
"""
return libmp.to_float(self._mpf_)

i.e. context's rounding mode is ignored and this function fallback to to_float() defaults (i.e. "round down", while context's defaults - "round to nearest"). In the mpmath:

    def __float__(s): return to_float(s._mpf_, rnd=s.context._prec_rounding[1]) 

Reproducer (see mpmath/mpmath#809):

from mpmath import mp, mpf, log
mp.prec=128
print(float(log(mpf('5.3e-7'))))

CPython3.12.4 + mpmath1.3.0 - -14.450388830400243
SageMathCell - -14.450388830400245

Simple fix is - adjust just this dunder. But I suggest switch to use the mpmath's upstread pure-python code. (1) "faster versions" are outdated c.f. the mpmath master, there are other problems, e.g. #36447 (2) using gmpy2.mpfr type as a drop-in replacement for the mpf is incorrect: these types actually are different (mpfr has signed zero, mpf has no limits for exponents range).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions