Implementing the modulus operator for floating-point numbers

submited by
Style Pass
2024-06-30 15:30:09

This article was very remotely inspired by Jacob Smith's article about color palettes. I started writing some Scheme code for generating color palettes, and I decided to first write some functions for converting between RGB and HSV formats. Then, I realized that Scheme (unlike Emacs Lisp, for example) doesn't support floating-point inputs in its modulus function.

I decided to write my own fmod function, starting with a simple version that only supported positive values, and eventually adding support for negative values, even though this was not needed when converting between RGB and HSV. I started writing the process in my scratch repository, but I think it has become interesting enough to deserve its own place in this blog.

The first function I wrote simply keeps subtracting the divisor to the dividend until the dividend is smaller than the divisor.

There are two main approaches for handling negative values: the one used by the fmod function in the math.h C header and the one used by the mod function in Emacs Lisp. Let's have a look at the outputs of both functions, and how they can be implemented.

Leave a Comment