Post Reply 
Square Root: Digit by Digit Algorithm
11-25-2022, 02:28 PM
Post: #7
RE: Square Root: Digit by Digit Algorithm
(11-25-2022 10:59 AM)Thomas Klemm Wrote:  The usage is rather clumsy but could be improved by wrapping these "lazy numbers" in a class.
Digits that have been calculated could be cached.
Maybe someone already did this?

Personally, I like the "clumsy" approach. It reminds user the delayed evaluation part.
mpmath does use the "clean" approach with many constants, by wrapping it in a class.

>>> import mpmath
>>> mpmath.ln2
<ln(2): 0.693147~>
>>> type(_)
<class 'mpmath.ctx_mp_python.constant'>

ctx_mp_python.py:
Code:
class _constant(_mpf):
    """Represents a mathematical constant with dynamic precision.
    When printed or used in an arithmetic operation, a constant
    is converted to a regular mpf at the working precision. A
    regular mpf can also be obtained using the operation +x."""

    def __new__(cls, func, name, docname=''):
        a = object.__new__(cls)
        a.name = name
        a.func = func
        a.__doc__ = getattr(function_docs, docname, '')
        return a

    def __call__(self, prec=None, dps=None, rounding=None):
        prec2, rounding2 = self.context._prec_rounding
        if not prec: prec = prec2
        if not rounding: rounding = rounding2
        if dps: prec = dps_to_prec(dps)
        return self.context.make_mpf(self.func(prec, rounding))

    @property
    def _mpf_(self):
        prec, rounding = self.context._prec_rounding
        return self.func(prec, rounding)

    def __repr__(self):
        return "<%s: %s~>" % (self.name, self.context.nstr(self(dps=15)))
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Square Root: Digit by Digit Algorithm - Albert Chan - 11-25-2022 02:28 PM



User(s) browsing this thread: 2 Guest(s)