Avoid fmod when rounding layout results to the pixel grid (#2041)

Summary:
copysign(x - trunc(x), x) is bit-identical to fmod(x, 1.0) for every
double but avoids the libm fmod loop, which is slow on Android's bionic.
roundValueToPixelGridDouble runs six times per node on every layout
pass.

Changelog: [Internal]

Reviewed By: cortinico

Differential Revision: D125600548

fbshipit-source-id: 7866bfb8619f7a6ec63bf799821a8c2270340a57

Author set to the author of react/yoga#2041; the commit on main carries the Yoga sync account.

Conflict resolved for 0.88-stable: kept the branch's variable name `fractial` (renamed to `fractional` on main in #58712). The change itself is identical to bf8d8c9a7a.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit bf8d8c9a7a)
This commit is contained in:
Tomek Zawadzki authored and t committed 2026-10-26 12:43:55 +00:00
1 parent bce6961a2b
commit 9b24e0df01
1 file changed
+9 -1
@@ -10,6 +10,8 @@
#include <yoga/algorithm/PixelGrid.h>
#include <yoga/numeric/Comparison.h>
#include <cmath>
namespace facebook::yoga {
namespace {
@@ -22,7 +24,13 @@ double roundValueToPixelGridDouble(
double scaledValue = value * pointScaleFactor;
// We want to calculate `fractial` such that `floor(scaledValue) = scaledValue
// - fractial`.
double fractial = fmod(scaledValue, 1.0);
//
// `copysign(x - trunc(x), x)` is bit-identical to `fmod(x, 1.0)` for every
// double (including -0.0, infinities and NaN) but avoids the libm `fmod`
// loop, which is slow on some platforms (e.g. Android's bionic). This
// function runs six times per node on every layout pass.
double fractial =
std::copysign(scaledValue - std::trunc(scaledValue), scaledValue);
if (fractial < 0) {
// This branch is for handling negative numbers for `value`.
//