Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Math expression evaluation error?



On 2015-01-12 19:18:22 +0300, ZyX wrote:
> 12.01.2015, 12:18, "Vincent Lefevre" <vincent@xxxxxxxxxx>:
> > It's only a notation problem. Unfortunately / was chosen (historically,
> > not by zsh) as the symbol for integer division. The shell expression
> > 1/2 + 1/2 just means:
> >
> >   integer_div(1,2) + integer_div(1,2)
> >
> > where integer_div is the integer division function, which gives 0.
> > This is perfectly correct math.
> 
> It is not integer division.

In POSIX, it is always an integer division.

> 1.0/2 and 1/2.0 will give the same result: 0.5.

because 1.0 and 2.0 don't have an integer type. Therefore the result is
unspecified by POSIX, and zsh chooses to do a floating-point division.

> If you want to see language with operator for integer division check
> out Python-3: it has / for always-floating-point-unless-overridden
> and // for always-integral-unless-overridden

For Python, but not for zsh, unfortunately. But this choice comes
from POSIX historical behavior (and perhaps earlier).

> I would rather call it “type-specific division”.

In zsh. In POSIX, it is *always* an integer division. There is no
floating-point there.

An alternative choice zsh could have done is to return an error
if the / operator is used in a floating-point context, and use a
different operator for the floating-point division. However the
use of / for integer division could still be surprising.

-- 
Vincent Lefèvre <vincent@xxxxxxxxxx> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)



Messages sorted by: Reverse Date, Date, Thread, Author