I wish to perform a modulo operation between two floating point integers in PostgreSQL. Specifically, I wish to enforce angle-arithmetic, e.g. forcing angles to lie in the interval [0,2*pi] after some mathematical operations.
I can see fmod or such is not officially supported in SQL. Is there any reasonable workaround?
1 Answer
It is trivial to create such a function yourself:
CREATE FUNCTION fmod (
dividend double precision,
divisor double precision
) RETURNS double precision
LANGUAGE sql IMMUTABLE AS
'SELECT dividend - floor(dividend / divisor) * divisor';
You can use that to solve your problem:
SELECT fmod(1000, 2.0 * pi());
fmod
-------------------
0.973536158445768
(1 row)
This function can be inlined, so it should be pretty efficient.