Subject: bug#30953: ‘min’ and ‘max’ behavior when mixing exact and inexact numbers.

From: Mark H Weaver <[email-masked]>
Date: Mon, 26 Mar 2018 22:21:25 -0400

tags 30953 + notabug
close 30953
thanks

Hi Mathieu,

Mathieu Lirzin <[email-masked]> writes:

> I am observing a unexpected behavior of ‘min’ and ‘max’:
>
> --8<---------------cut here---------------start------------->8---
> scheme@(guile-user)> (min 1 2.4)
> $2 = 1.0
> scheme@(guile-user)> (min 1/2 4.0)
> $7 = 0.5
> scheme@(guile-user)> (max 4 3.5)
> $4 = 4.0
> --8<---------------cut here---------------end--------------->8---
>
> I would expect the results to be integers instead.

1.0 and 4.0 _are_ integers, in the terminology of both Scheme and
mathematics.  However, they are _inexact_ integers.

I'm not sure why you would expect (min 1/2 4.0) to return an integer.

By the result of exactness propagation in Scheme, these results must be
inexact, because the results depend on the value of an inexact argument.
For example, in (min 1 2.4), if the 2.4 were replaced with 0.8, then the
result would be 0.8 instead of 1.0.  It's entirely possible that the
inexact arithmetic leading to 2.4 might have a maximum error greater
than 1.4.

The idea is that if Scheme tells you that the result of some computation
is exact, then it could in principle be proved to be the true
mathematical result, and therefore known to be unaffected by any inexact
computation.

So, (min 1 2.4) could only return an exact 1 if it were somehow known
that the 2.4 has a maximum error of 1.4.  I suspect you are thinking to
yourself "the 2.4 might be imprecise, but surely it's not so far off to
affect the result here."  However, there's no upper bound on the error
of an inexact number, when one considers the entire history of inexact
operations that led to it.

For details, see R5RS section 6.2.2 (Exactness), R6RS section 11.7.1
(Propagation of exactness and inexactness), and R7RS section 6.2.2
(Exactness).

> AIUI the
> implementation of the ‘min’ procedure should to be equivalent to:
>
>   (define (min val . rest)
>     (let loop ((x val) (other rest))
>       (match other
>         (() x)
>         ((y . rest) (loop (if (< x y) x y) rest)))))

This would violate the exactness propagation rules.

> Maybe there is a good performance reason for the current behavior.  If
> that's the case then it should be specified in the manual that exact
> numbers are converted to real numbers when at least one of the arguments
> is inexact.

In Scheme (and mathematics), 1 and 1/2 are considered real numbers, and
1.0 is both a real number and an integer.  In Scheme, the only
difference between 1 and 1.0 is that 1 is exact and 1.0 is inexact.

Lesser programming languages say that 1 is not a real number and that
1.0 is not an integer, but from a mathematical point of view, that's
nonsense :)

     Regards,
       Mark