From 76bdbeb862f64aa8b8773b5183d28b3eb1bbfc8a Mon Sep 17 00:00:00 2001 From: Edward Welbourne Date: Mon, 31 Jan 2022 18:39:07 +0100 Subject: [PATCH] Document float-to-qfloat16's rounding more carefully MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Having just spent another afternoon wrapping my head around why this code is correct, I chose to save the next person (quite possibly me) faced with it the slowest half of the effort that went into doing so. This amends commit d3ff95dcb84861e8f42b480910d822b4ca8715b1 Change-Id: If0fcd2fb1fff5e99b1046d07039169e928fda9e4 Reviewed-by: Tor Arne Vestbø Reviewed-by: Allan Sandfeld Jensen --- src/corelib/global/qfloat16.h | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/corelib/global/qfloat16.h b/src/corelib/global/qfloat16.h index a1785638890..8361dd8764f 100644 --- a/src/corelib/global/qfloat16.h +++ b/src/corelib/global/qfloat16.h @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2021 The Qt Company Ltd. +** Copyright (C) 2022 The Qt Company Ltd. ** Copyright (C) 2016 by Southwest Research Institute (R) ** Contact: http://www.qt-project.org/legal ** @@ -275,8 +275,12 @@ inline qfloat16::qfloat16(float f) noexcept if (mantissa) // keep nan from truncating to inf mantissa = qMax(1U << shift, mantissa); } else { - // round half to even + // Round half to even. First round up by adding one in the most + // significant bit we'll be discarding: mantissa += round; + // If the last bit we'll be keeping is now set, but all later bits are + // clear, we were at half and shouldn't have rounded up; decrement will + // clear this last kept bit. Any later set bit hides the decrement. if (mantissa & (1 << shift)) --mantissa; }