// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2020 C. Antonio Sanchez <cantonios@google.com> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
// Utilities for generating random numbers without overflows, which might // otherwise result in undefined behavior.
// Floating-point to integer, narrowing precision. template <typename SrcScalar, typename TgtScalar> struct random_without_cast_overflow<
SrcScalar, TgtScalar, typename internal::enable_if<
!NumTraits<SrcScalar>::IsInteger && !NumTraits<SrcScalar>::IsComplex && NumTraits<TgtScalar>::IsInteger &&
(std::numeric_limits<TgtScalar>::digits > std::numeric_limits<SrcScalar>::digits)>::type> { static SrcScalar value() { // NOTE: internal::random<T>() is limited by RAND_MAX, so random<int64_t> is always within that range. // This prevents us from simply shifting bits, which would result in only 0 or -1. // Instead, keep least-significant K bits and sign. staticconst TgtScalar KeepMask = (static_cast<TgtScalar>(1) << std::numeric_limits<SrcScalar>::digits) - 1; const TgtScalar a = internal::random<TgtScalar>(); returnstatic_cast<SrcScalar>(a > TgtScalar(0) ? (a & KeepMask) : -(a & KeepMask));
}
};
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.