Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Floating point modulus
On Jan 10, 9:46pm, Ray Andrews wrote:
}
} Speaking of testing, I can't get modulus to work nohow.
}
} $ echo $(( 2.5 ));
} 2.5
}
} $ echo $(( 2.5 % 2 ));
} 0
}
} ... If I'm doing something stupid there ...
Zsh implements the C modulus operator (%) directly, and it's defined
only on integers. If you try that in C it won't even compile:
error: invalid operands to binary %
Consequently the operands are silently converted to integers, instead
of the shell throwing an error.
The expectation is that you will know that zsh math is C math (same
as for why things are integer by default) and that you must do:
$ zmodload zsh/mathfunc
$ echo $(( fmod(2.5, 2) ))
0.5
The following patch would instead silently substitute the fmod() call
when using the % operator on a float. I won't commit it without some
further discussion from the group. With more effort it could be made
to do this only when FORCE_FLOAT is in effect, though I'm not sure
how many such special-cases we want to manage.
diff --git a/Src/math.c b/Src/math.c
index 438a170..6d096e0 100644
--- a/Src/math.c
+++ b/Src/math.c
@@ -288,11 +288,11 @@ static int type[TOKCOUNT] =
{
/* 0 */ LR, LR|OP_OP|OP_OPF, RL, RL, RL|OP_OP|OP_OPF,
/* 5 */ RL|OP_OP|OP_OPF, RL, RL, LR|OP_A2IO, LR|OP_A2IO,
-/* 10 */ LR|OP_A2IO, LR|OP_A2, LR|OP_A2, LR|OP_A2IO, LR|OP_A2,
+/* 10 */ LR|OP_A2IO, LR|OP_A2, LR|OP_A2, LR|OP_A2, LR|OP_A2,
/* 15 */ LR|OP_A2, LR|OP_A2IO, LR|OP_A2IO, LR|OP_A2IR, LR|OP_A2IR,
/* 20 */ LR|OP_A2IR, LR|OP_A2IR, LR|OP_A2IR, LR|OP_A2IR, BOOL|OP_A2IO,
/* 25 */ BOOL|OP_A2IO, LR|OP_A2IO, RL|OP_OP, RL|OP_OP, RL|OP_E2,
-/* 30 */ RL|OP_E2, RL|OP_E2, RL|OP_E2, RL|OP_E2, RL|OP_E2IO,
+/* 30 */ RL|OP_E2, RL|OP_E2, RL|OP_E2, RL|OP_E2, RL|OP_E2,
/* 35 */ RL|OP_E2IO, RL|OP_E2IO, RL|OP_E2IO, RL|OP_E2IO, RL|OP_E2IO,
/* 40 */ BOOL|OP_E2IO, BOOL|OP_E2IO, RL|OP_A2IO, RL|OP_A2, RL|OP_OP,
/* 45 */ RL, RL, LR|OP_OPF, LR|OP_OPF, RL|OP_A2,
@@ -1133,7 +1133,9 @@ op(int what)
* Any integer mod -1 is the same as any integer mod 1
* i.e. zero.
*/
- if (b.u.l == -1)
+ if (c.type == MN_FLOAT)
+ c.u.d = fmod(a.u.d, b.u.d);
+ else if (b.u.l == -1)
c.u.l = 0;
else
c.u.l = a.u.l % b.u.l;
Messages sorted by:
Reverse Date,
Date,
Thread,
Author