fmod
Truncated floating-point remainder; the result takes the sign of the dividend.
Test fmod in a live shader
Open the playground, start from a visual preset, and wire fmod into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo Pending
The fmod function returns the remainder of x / y with the quotient truncated toward zero. The result has the same sign as x. This matches HLSL and Metal fmod and C's fmod, and differs from mod, whose result takes the sign of y.
Signature
fmod :: (T x, T y) -> T {...}
Where T can be float, float2, float3, or float4.
Parameters
| Parameter | Type | Description |
|---|---|---|
x | T | The dividend |
y | T | The divisor |
Return Value
Returns x - y * trunc(x / y), component-wise.
x | y | mod(x, y) | fmod(x, y) |
|---|---|---|---|
5.5 | 2.0 | 1.5 | 1.5 |
-5.5 | 2.0 | 0.5 | -1.5 |
5.5 | -2.0 | -0.5 | 1.5 |
Example
// Signed phase that keeps the direction of travel:
// negative offsets stay negative instead of wrapping into [0, period).
float phase = fmod(offset, period);
float wave = sin(phase / period * 6.28318);
Which one to use
Use mod to wrap values into a repeating range such as UVs or angles. Use fmod when you are porting HLSL or Metal code that relies on the sign of the dividend.
Compiled Output
fmod compiles to SPIR-V OpFRem.
When compiled to GLSL (GLSL has no fmod):
x - y * trunc(x / y)
When compiled to HLSL and Metal:
fmod(x, y)