Files
mp-units/test/runtime/truncation_test.cpp
T
Mateusz Pusz efbc844199 fix: fixed-point arithmetic for integer unit conversions (#580) (#764)
* Fix #580: use fixed-point arithmetic for integer unit conversions

Introduce a fixed-point implementation for unit conversions involving
integer representations, avoiding loss of significant digits that
previously occurred when the conversion factor was not a whole number.

New files:
- src/core/include/mp-units/bits/fixed_point.h: double_width_int<T> and
  fixed_point<T,n> types for exact rational scaling of integer values.
  Uses __int128 when available (__SIZEOF_INT128__) for 64-bit integers.
- src/core/include/mp-units/framework/scaling.h: public scaling_traits<>
  customization point and scale<To>(M, value) free function. Provides
  built-in specializations for floating-point and integer-like types.
- test/static/fixed_point_test.cpp: static assertions for the new types.
- test/runtime/fixed_point_test.cpp: runtime arithmetic edge-case tests.

Modified:
- sudo_cast.h: replace hand-rolled conversion_value_traits / sudo_cast_value
  machinery with a single scale<To::rep>(c_mag, ...) call.
- representation_concepts.h: add MagnitudeScalable concept; replace
  ComplexScalar with HasComplexOperations (which is its definition).
- customization_points.h: add unspecified_rep tag and declare the primary
  scaling_traits<> template.
- framework.h / CMakeLists.txt: wire in the new headers.
- hacks.h: add MP_UNITS_DIAGNOSTIC_IGNORE_PEDANTIC and
  MP_UNITS_DIAGNOSTIC_IGNORE_SIGN_CONVERSION macros.
- example/measurement.cpp: add scaling_traits specializations for
  measurement<T> to demonstrate the customization point.
- test/static/{international,usc}_test.cpp: disable two tests that are
  blocked on issue #614.

Co-authored-by: Tobias Hanhart <burnpanck@users.noreply.github.com>

* Fix value_Type typo in floating_point_scaling_factor_type specialization

The partial specialization for types with a nested value_type used
'value_Type' (capital T) instead of 'value_type', making the entire
specialization dead code as the requires-clause could never be satisfied.

Also fix 'mantiassa' -> 'mantissa' in the adjacent comment.

* Fix docstring typos in scaling_traits documentation

- 'quantitiy' -> 'quantity'
- 'dictatet' -> 'dictated'
- 'convetrible' -> 'convertible'
- 'implemenation' -> 'implementation'
- 'availabe' -> 'available'

* Fix conflict resolution error: keep ComplexScalar name from master

When resolving the merge conflict in representation_concepts.h, the
PR's renamed version of the concept ('HasComplexOperations') was used
instead of master's established name ('ComplexScalar'). The two concepts
are semantically equivalent — burnpanck simply renamed it in his branch.

Revert to the canonical 'ComplexScalar' name while retaining the new
'MagnitudeScalable' concept which was the actual addition from the PR.

* Fix measurement.cpp: remove duplicate class definition from merge

The PR branched from a version where measurement<T> was defined inline
in measurement.cpp. Master later moved the class to example/include/
measurement.h and changed measurement.cpp to #include that header.

The squash merge therefore introduced a duplicate definition: the class
from the header and the PR's inline class were both visible, causing
an 'ambiguous reference' error. Remove the now-redundant inline class;
the scaling_traits specializations added by the PR work correctly with
the class from measurement.h.

* style: pre-commit

* docs: chapters anchors improved in the "custom representation" chapter

* docs: value conversions chapter improved

* refactor: scaling support refactored

* fix: clang-16 crash fixed

* docs: `measurement` example documentation updated to match changes

* fix: use exact wide-integer arithmetic for rational unit conversions on all platforms

On ARM / Apple Silicon, long double == double (64-bit mantissa).  The old
fixed_point<T>(long double) initialiser lost ~12 bits of precision for 64-bit
integer types when representing the scaling ratio, producing an error of ~49
units for the 10/9 (degree → gradian) conversion with a 10^18 input value.

Fix by splitting the integer-path else-branch into two cases:

  • Pure rational M (is_integral(M * (denominator(M) / numerator(M))) == true):
    use (value * numerator) / denominator via double_width_int_for_t<> arithmetic.
    This is exact on every platform regardless of long double width.

  • Irrational M (involves π etc.): keep the long double fixed_point approximation.
    These conversions are inherently approximate; small values still produce correct
    truncated results on all platforms.

Update the test comment to reflect the new exact-arithmetic path.

Fixes CI failures on clang-18/ARM and apple-clang-16.

* fix: replace floating-point TeX-point test with exact integer equivalent

72.27 is not exactly representable as double (it rounds to 72.2699...96).
Multiplying by the conversion factor 100/7227 via long double gives a result
≥ 1.0 on x86 (80-bit long double, 64-bit mantissa) only by chance, but
0.99999...978 on ARM / Apple Silicon where long double == double (52-bit).

The correct mathematical statement is: 7227 tex_point = 100 inch (exact
rational relationship).  Use that integer form instead of the inexact 72.27
double literal so the test is correct and platform-independent.

---------

Co-authored-by: Tobias Hanhart <burnpanck@users.noreply.github.com>
2026-03-07 21:02:37 +01:00

163 lines
6.6 KiB
C++

// The MIT License (MIT)
//
// Copyright (c) 2018 Mateusz Pusz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "almost_equals.h"
#include <catch2/catch_template_test_macros.hpp>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers.hpp>
#include <mp-units/ext/format.h>
#ifdef MP_UNITS_IMPORT_STD
import std;
#else
#include <limits>
#include <numbers>
#endif
#ifdef MP_UNITS_MODULES
import mp_units;
#else
#include <mp-units/systems/angular.h>
#endif
using namespace mp_units;
using namespace mp_units::angular;
using namespace mp_units::angular::unit_symbols;
inline constexpr struct half_revolution final : named_unit<"hrev", π * radian> {
} half_revolution;
inline constexpr auto hrev = half_revolution;
TEST_CASE("value_cast should not truncate for valid inputs", "[value_cast]")
{
SECTION("num > den > 1, irr = 1")
{
REQUIRE_THAT(value_cast<grad>(9 * deg), AlmostEquals(10 * grad));
REQUIRE_THAT(value_cast<grad>(360 * deg), AlmostEquals(400 * grad));
}
SECTION("1 < num < den, irr = 1")
{
REQUIRE_THAT(value_cast<deg>(10 * grad), AlmostEquals(9 * deg));
REQUIRE_THAT(value_cast<deg>(400 * grad), AlmostEquals(360 * deg));
}
SECTION("num > den = 1, irr > 1")
{
REQUIRE_THAT(value_cast<rad>(1 * rev), AlmostEquals(6 * rad));
REQUIRE_THAT(value_cast<rad>(5 * rev), AlmostEquals(31 * rad));
REQUIRE_THAT(value_cast<rad>(10 * rev), AlmostEquals(63 * rad));
REQUIRE_THAT(value_cast<rad>(20 * rev), AlmostEquals(126 * rad));
}
SECTION("1 = num < den, irr < 1")
{
REQUIRE_THAT(value_cast<rev>(6 * rad), AlmostEquals(1 * rev));
REQUIRE_THAT(value_cast<rev>(31 * rad), AlmostEquals(5 * rev));
REQUIRE_THAT(value_cast<rev>(63 * rad), AlmostEquals(10 * rev));
REQUIRE_THAT(value_cast<rev>(126 * rad), AlmostEquals(20 * rev));
}
SECTION("rational = 1, irrational > 1")
{
REQUIRE_THAT(value_cast<rad>(1 * hrev), AlmostEquals(3 * rad));
REQUIRE_THAT(value_cast<rad>(10 * hrev), AlmostEquals(31 * rad));
REQUIRE_THAT(value_cast<rad>(20 * hrev), AlmostEquals(63 * rad));
REQUIRE_THAT(value_cast<rad>(40 * hrev), AlmostEquals(126 * rad));
}
SECTION("rational = 1, irrational < 1")
{
REQUIRE_THAT(value_cast<hrev>(3 * rad), AlmostEquals(1 * hrev));
REQUIRE_THAT(value_cast<hrev>(31 * rad), AlmostEquals(10 * hrev));
REQUIRE_THAT(value_cast<hrev>(63 * rad), AlmostEquals(20 * hrev));
REQUIRE_THAT(value_cast<hrev>(126 * rad), AlmostEquals(40 * hrev));
}
SECTION("rational > 1, irrational < 1")
{
// rad -> deg: factor = 180/π ≈ 57.296
REQUIRE_THAT(value_cast<deg>(1 * rad), AlmostEquals(57 * deg));
REQUIRE_THAT(value_cast<deg>(3 * rad), AlmostEquals(171 * deg));
REQUIRE_THAT(value_cast<deg>(6 * rad), AlmostEquals(343 * deg));
REQUIRE_THAT(value_cast<deg>(9 * rad), AlmostEquals(515 * deg));
}
SECTION("rational < 1, irrational > 1")
{
// deg -> rad: factor = π/180 ≈ 0.01745
REQUIRE_THAT(value_cast<rad>(180 * deg), AlmostEquals(3 * rad));
REQUIRE_THAT(value_cast<rad>(360 * deg), AlmostEquals(6 * rad));
REQUIRE_THAT(value_cast<rad>(540 * deg), AlmostEquals(9 * rad));
REQUIRE_THAT(value_cast<rad>(1080 * deg), AlmostEquals(18 * rad));
}
}
TEMPLATE_TEST_CASE("value_cast should not overflow internally for valid inputs", "[value_cast]", std::int8_t,
std::uint8_t, std::int16_t, std::uint16_t, std::int32_t, std::uint32_t)
{
// max()/20: small enough so that none of the tested factors are likely to cause overflow, but still be nonzero;
// the "easy" test to verify the test itself is good.
std::vector<TestType> test_values = {std::numeric_limits<TestType>::max() / 20,
std::numeric_limits<TestType>::max() - 1};
if (std::is_signed_v<TestType>) {
test_values.push_back(std::numeric_limits<TestType>::min() + 1);
}
for (TestType tv : test_values) {
SECTION("grad <-> deg")
{
auto deg_number = static_cast<TestType>(std::trunc(0.9 * tv));
auto grad_number = static_cast<TestType>(std::round(deg_number / 0.9));
INFO(MP_UNITS_STD_FMT::format("{} deg ~ {} grad", deg_number, grad_number));
REQUIRE_THAT(value_cast<grad>(deg_number * deg), AlmostEquals(grad_number * grad));
REQUIRE_THAT(value_cast<deg>(grad_number * grad), AlmostEquals(deg_number * deg));
}
SECTION("rad <-> rev")
{
auto rev_number = static_cast<TestType>(std::trunc(0.5 * std::numbers::inv_pi * tv));
auto rad_number = static_cast<TestType>(std::round(2 * std::numbers::pi * rev_number));
INFO(MP_UNITS_STD_FMT::format("{} rev ~ {} rad", rev_number, rad_number));
REQUIRE_THAT(value_cast<rad>(rev_number * rev), AlmostEquals(rad_number * rad));
REQUIRE_THAT(value_cast<rev>(rad_number * rad), AlmostEquals(rev_number * rev));
}
SECTION("deg -> rad")
{
// The factor π/180 has rational numerator 1, so the compile-time
// scaling_overflows_non_zero_values check passes for all integral
// representation types — any degree value can be converted to radians
// without internal intermediate overflow.
// (The reverse, rad -> deg, has factor 180/π whose rational numerator 180
// exceeds the range of int8_t, so that direction is correctly rejected at
// compile time for that type and is covered by the narrower-value tests
// for types where 180 fits within the range.)
auto deg_number = tv;
auto rad_number = static_cast<TestType>(std::trunc(std::numbers::pi / 180.0 * deg_number));
INFO(MP_UNITS_STD_FMT::format("{} deg ~ {} rad", deg_number, rad_number));
REQUIRE_THAT(value_cast<rad>(deg_number * deg), AlmostEquals(rad_number * rad));
}
}
}