## digitalmars.D - [Suggestion] floor-mod and floor-divide

- Stewart Gordon <smjg_1998 yahoo.com> Nov 29 2004

The C definitions of the / and % operators (which D mimics) have always seemed to me to be not quite right in their handling of negative operands. I've just been looking through my archives at this thread on the issue: http://google.com/groups?threadm=100320001202113511%25yahoo_com francis.uy It would therefore be nice to invent a few new operators to do floor-mod and floor-divide. floor-mod is like the standard % operator (aka trunc-mod) except that the result has the sign of the right operand. So, while trunc-mod does this 23 % 5 == 3 -23 % 5 == -3 23 % -5 == 3 -23 % -5 == -3 floor-mod would do this 23 %% 5 == 3 -23 %% 5 == 2 23 %% -5 == -2 -23 %% -5 == -3 and hence for a given right operand, be periodic over the entire number line. floor-divide is simply division always rounded down, rather than towards zero. 23 /% 5 == 4 -23 /% 5 == -5 23 /% -5 == -5 -23 /% -5 == 4 (Maybe we can come up with a nicer-looking symbol for this operation....) This satisfies the identity (x /% y) * y + (x %% y) == x just as the regular / and % do on integers. Of course, for floating points, the same floor-mod operator would apply, but I guess floor-divide isn't really applicable to the same extent. I guess we could debate what /% (or whatever we decide to call it) should mean on floating point types, or if it should be defined at all. I don't know how many CPUs have built-in floor-mod and floor-divide instructions, but they would be used if compiling for a machine with these available. Otherwise, the compiler would generate code to implement the operations in terms of available machine instructions. Of course, the operators would be overloadable - maybe with opFloorMod and opFloorDiv? Stewart.

Nov 29 2004