I just discovered that vim obviously allows division by zero:
:let a=42/0
:echo a
prints 2147483647
(which is the value of a
).
Is this documented somewhere and why does vim allow division by zero?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityThis behavior is documented under eval section:
When dividing a Number by zero the result depends on the value:
0 / 0 = -0x80000000 (like NaN for Float)
>0 / 0 = 0x7fffffff (like positive infinity)
<0 / 0 = -0x7fffffff (like negative infinity)
(before Vim 7.2 it was always 0x7fffffff)
Here is why :
42 / 0 tends to +infinity
And how does Vim represent the largest number available ?
2147483647
See :h limits
Furthermore, the float2nr
function documentation states :
When the value of {expr} is out of range for a |Number| the
result is truncated to 0x7fffffff or -0x7fffffff. NaN results
in -0x80000000.
So you have here your 2 numbers : + 2147483647
and - 2147483647
.
The last number -2147483648
is used for representing the NaN
value.
This is confirmed by the eval
section on it (mea culpa: @cuonglm posted it just before me) :
When dividing a Number by zero the result depends on the value:
0 / 0 = -0x80000000 (like NaN for Float)
>0 / 0 = 0x7fffffff (like positive infinity)
<0 / 0 = -0x7fffffff (like negative infinity)
As @VanLaser stated, this only work for integer, for floating point number you have more consistency :
1/0.0 = inf
1/0.0 + 1 = inf
1/0.0 - 1 = inf
-1/0.0 = -inf
-1/0.0 - 1 = -inf
-1/0.0 + 1 = -inf
This behavior is useful in Calculus when using something called a Limit.
Lim n -> 0^+ of 1/n = +inf
This can also be written as: As n -> 0^+, 1/n -> +inf
It is read like so.. As n approaches zero from the right, the function 1/n approaches positive infinity.
To see a visual explanation of this reasoning, pop over to http://www.wolframalpha.com/input/?i=limit+n-%3E0+of+1%2Fn
As for Vim-script specifically, AFAIK not many people do much more than logic and integer arithmetic with it. It could be the case that this behavior seemed like a good idea at the time, and is merely a legacy artifact at this point.
:echo 42/0.0
to see another result :)