Square Root: Digit by Digit Algorithm
11-25-2022, 02:28 PM
Post: #7
 Albert Chan Senior Member Posts: 2,711 Joined: Jul 2018
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.

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)))
 « Next Oldest | Next Newest »

 Messages In This Thread Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-25-2022, 06:02 AM RE: Square Root: Digit by Digit Algorithm - brouhaha - 11-25-2022, 06:33 AM RE: Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-25-2022, 07:51 AM RE: Square Root: Digit by Digit Algorithm - brouhaha - 11-25-2022, 09:30 AM RE: Square Root: Digit by Digit Algorithm - BruceH - 11-27-2022, 10:44 PM RE: Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-25-2022, 10:59 AM RE: Square Root: Digit by Digit Algorithm - Albert Chan - 11-25-2022 02:28 PM RE: Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-25-2022, 11:57 AM RE: Square Root: Digit by Digit Algorithm - ttw - 11-25-2022, 02:40 PM RE: Square Root: Digit by Digit Algorithm - Albert Chan - 11-25-2022, 03:48 PM RE: Square Root: Digit by Digit Algorithm - EdS2 - 11-25-2022, 05:31 PM RE: Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-25-2022, 07:05 PM RE: Square Root: Digit by Digit Algorithm - Thomas Klemm - 11-26-2022, 01:15 PM RE: Square Root: Digit by Digit Algorithm - ttw - 11-27-2022, 07:34 PM

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