Precision Tail-off?

Weatherby,Gerard gweatherby at uchc.edu
Wed Feb 15 09:36:24 EST 2023


All languages that use IEEE floating point will indeed have the same limitations, but it is not true that Python3 only uses IEEE floating point. Using the Decimal class and cribbing a method from StackOverflow, https://stackoverflow.com/questions/47191533/how-to-efficiently-calculate-cube-roots-using-decimal-in-python


import decimal
from decimal import Decimal

decimal.getcontext().prec = 1_000_000


def cube_root(A: Decimal):
    guess = (A - Decimal(1)) / Decimal(3)
    x0 = (Decimal(2) * guess + A / Decimal(guess * guess)) / Decimal(3.0)
    while 1:
        xn = (Decimal(2) * x0 + A / Decimal(x0 * x0)) / Decimal(3.0)
        if xn == x0:
            break
        x0 = xn
    return xn


float_root = 5 ** (1.0 / 3)
float_r3 = float_root * float_root * float_root
print(5 - float_r3)
five = Decimal(5.0)
r = cube_root(five)
decimal_r3 = r * r * r
print(5 - decimal_r3)

----
8.881784197001252e-16
1E-999999

From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Michael Torrie <torriem at gmail.com>
Date: Tuesday, February 14, 2023 at 5:52 PM
To: python-list at python.org <python-list at python.org>
Subject: Re: Precision Tail-off?
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***

On 2/14/23 00:09, Stephen Tucker wrote:
> I have two questions:
> 1. Is there a straightforward explanation for this or is it a bug?
To you 1/3 may be an exact fraction, and the definition of raising a
number to that power means a cube root which also has an exact answer,
but to the computer, 1/3 is 0.333333333333333 repeating in decimal,
which is some other fraction in binary.  And even rational numbers like
0.2, which are precise and exact, are not in binary
(0.01010101010101010101).  0.2 is .0011011011011011011 on and on forever.

IEEE floating point has very well known limitations.  All languages that
use IEEE floating point will be subject to these limitations.  So it's
not a bug in the sense that all languages will exhibit this behavior.

> 2. Is the same behaviour exhibited in Python 3.x?
Yes. And Java, C++, and any other language that uses IEEE floating point.

--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jjhLqksliV_IjxQAHxXvdnOLB00sJU_hfHNIfK2U1NK-yO2X2kOxJtk6nbqEzXZkyOPBOaMdIlz_sHGkpA$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!jjhLqksliV_IjxQAHxXvdnOLB00sJU_hfHNIfK2U1NK-yO2X2kOxJtk6nbqEzXZkyOPBOaMdIlz_sHGkpA$>


More information about the Python-list mailing list