Ask Your Question

svat's profile - activity

2020-09-24 14:29:23 +0200 commented question Incorrect results for comparison expression

Incidentally, x.n(digits=6) instead of giving something like 0.0000209431 gives 1024.00, which is scary.

2020-09-24 14:17:27 +0200 commented answer Incorrect results for comparison expression

Unfortunately the Sage versions I have access to will all happily declare a and b to be equal even when they are not (see comments under your answer), so the best I could do was to add an assumption to the function that they are not equal.

2020-09-23 21:26:28 +0200 received badge  Editor (source)
2020-09-23 21:23:50 +0200 answered a question Incorrect results for comparison expression

I found a work-around in a question I had myself asked about 5 years ago (but apparently forgotten its lesson): "Incorrect result for comparison (precision issues?)" at ask.sagemath.org/question/32371 — the solution is to avoid the "<" operator for comparison (what a gotcha!), and define one's own smaller function:

def smaller(a, b):
    '''Returns True if a < b (and False if b < a). Assumes that a != b.'''
    prec = 53
    while prec < 100000:
        R = RealIntervalField(prec)
        try:
            R(a).intersection(R(b))
        except ValueError:
            return R(a) < R(b)
        else:
            #print '{} bits of precision is not enough'.format(prec)
            prec += prec // 10
    raise Exception('100000 bits of precision was not enough for comparing: ', a, b, ' -- Possibly they are equal')

Then it works correctly:

sage: bool(smaller(1/47749, -5564456128*e + 15125759978))
True

Note that this function assumes that a ≠ b:

sage: smaller(pi/4, 4*arctan(1/5) - arctan(1/239))
...
Exception: ('100000 bits of precision was not enough for comparing: ', 1/4*pi, 4*arctan(1/5) - arctan(1/239), ' -- Possibly they are equal')
2020-09-23 19:16:18 +0200 asked a question Incorrect results for comparison expression

Sage incorrectly evaluates bool(1/47749 <= -5564456128*e + 15125759978) as False.

In more detail, consider this:

sage: x = -5564456128*e + 15125759978
sage: (1/47749).n(digits=6)
0.0000209428
sage: x.n(digits=20)
0.000020943072740919888020
sage: bool(1/47749 <= x)
False

What is going on? Why does the last boolean evaluate to False? This results in the failure of the assertion that 1/ceil(1/x) <= x, which should be true mathematically.

Is there a way to compare two quantities that will result in a correct answer, using as much precision as necessary?