Intrinsics1 min read

fmod

Truncated floating-point remainder; the result takes the sign of the dividend.

Reading Time
1 min
Word Count
178
Sections
6
Try It Live

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 Playground

Live Demo Pending

This intrinsic does not yet have a self-contained interactive preview. Compute-only and external-resource intrinsics need a different demo path than the current fragment and 3D showcases.

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

bwsl
fmod :: (T x, T y) -> T {...}

Where T can be float, float2, float3, or float4.

Parameters

ParameterTypeDescription
xTThe dividend
yTThe divisor

Return Value

Returns x - y * trunc(x / y), component-wise.

xymod(x, y)fmod(x, y)
5.52.01.51.5
-5.52.00.5-1.5
5.5-2.0-0.51.5

Example

bwsl
// 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):

glsl
x - y * trunc(x / y)

When compiled to HLSL and Metal:

hlsl
fmod(x, y)

See Also

  • mod - Floored remainder, sign of the divisor
  • trunc - Round toward zero
  • Operators - Integer % also takes the sign of the dividend