# Why do mpmath mpf values compare strangely to Integers?

This post is a wiki. Anyone with karma >750 is welcome to improve it.

With both sage 6.8 and 7.1.beta3 on OSX 10.10.5 I get this odd result:

sage: import mpmath
sage: max(Integer(0), mpmath.mpf(-1))
0
sage: max(mpmath.mpf(-1), Integer(0))
mpf('-1.0')
sage: Integer(0) < mpmath.mpf(-1)
True


The maximum of 0 and -1 should be 0, although I'm not sure if it should be Integer(0) or mpf(0).

Am I missing something about how sage expects me to handle arbitrary-precision floating-point numbers?

edit retag close merge delete

Sort by ยป oldest newest most voted

The max function in Sage is the Python built-in function max, which relies on comparisons.

This stackoverflow answer explains roughly how it works. To compute max(a, b),

1. Provisionally set the result to the first value, a.
2. If b > a, change the result to b.
3. Return the result.

In step 2, comparing objects of different types is tricky.

One would expect objects representing real numbers to compare well even if they are of different types. In your example, this fails.

As a practical suggestion: to compare numbers using < and >, first take them to a common parent where such comparison is defined properly.

In your case, if a = Integer(0) and b = mpmath.mpf(-1), you could compare RDF(a)and RDF(b) instead of comparing a and b. (Note: RDF stands for "real double field", a fast and reliable approximation to the field of real numbers, recommended in many contexts.)

sage: import mpmath
sage: a, b = Integer(0), mpmath.mpf(-1)
sage: max(a, b)
0
sage: max(b, a)
mpf('-1.0')
sage: max(RDF(a), RDF(b))
0.0
sage: max(RDF(b), RDF(a))
0.0

more