summaryrefslogtreecommitdiffstats
path: root/src/corelib/global/qnumeric.cpp
blob: a46039c5da5fddb6aec24ad0d4441aa4257ba9b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qnumeric.h"
#include "qnumeric_p.h"
#include <string.h>

QT_BEGIN_NAMESPACE

/*!
    \headerfile <QtNumeric>
    \inmodule QtCore
    \title Qt Numeric Functions

    \brief The <QtNumeric> header file provides common numeric functions.

    The <QtNumeric> header file contains various numeric functions
    for comparing and adjusting a numeric value.
*/

/*!
    Returns \c true if the double \a {d} is equivalent to infinity.
    \relates <QtNumeric>
    \sa qInf()
*/
Q_CORE_EXPORT bool qIsInf(double d) { return qt_is_inf(d); }

/*!
    Returns \c true if the double \a {d} is not a number (NaN).
    \relates <QtNumeric>
*/
Q_CORE_EXPORT bool qIsNaN(double d) { return qt_is_nan(d); }

/*!
    Returns \c true if the double \a {d} is a finite number.
    \relates <QtNumeric>
*/
Q_CORE_EXPORT bool qIsFinite(double d) { return qt_is_finite(d); }

/*!
    Returns \c true if the float \a {f} is equivalent to infinity.
    \relates <QtNumeric>
    \sa qInf()
*/
Q_CORE_EXPORT bool qIsInf(float f) { return qt_is_inf(f); }

/*!
    Returns \c true if the float \a {f} is not a number (NaN).
    \relates <QtNumeric>
*/
Q_CORE_EXPORT bool qIsNaN(float f) { return qt_is_nan(f); }

/*!
    Returns \c true if the float \a {f} is a finite number.
    \relates <QtNumeric>
*/
Q_CORE_EXPORT bool qIsFinite(float f) { return qt_is_finite(f); }

#if QT_CONFIG(signaling_nan)
/*!
    Returns the bit pattern of a signalling NaN as a double.
    \relates <QtNumeric>
*/
Q_CORE_EXPORT double qSNaN() { return qt_snan(); }
#endif

/*!
    Returns the bit pattern of a quiet NaN as a double.
    \relates <QtNumeric>
    \sa qIsNaN()
*/
Q_CORE_EXPORT double qQNaN() { return qt_qnan(); }

/*!
    Returns the bit pattern for an infinite number as a double.
    \relates <QtNumeric>
    \sa qIsInf()
*/
Q_CORE_EXPORT double qInf() { return qt_inf(); }

/*!
    \fn int qFpClassify(double val)
    \fn int qFpClassify(float val)

    \relates <QtNumeric>
    Classifies a floating-point value.

    The return values are defined in \c{<cmath>}: returns one of the following,
    determined by the floating-point class of \a val:
    \list
    \li FP_NAN not a number
    \li FP_INFINITE infinities (positive or negative)
    \li FP_ZERO zero (positive or negative)
    \li FP_NORMAL finite with a full mantissa
    \li FP_SUBNORMAL finite with a reduced mantissa
    \endlist
*/
Q_CORE_EXPORT int qFpClassify(double val) { return qt_fpclassify(val); }
Q_CORE_EXPORT int qFpClassify(float val) { return qt_fpclassify(val); }


/*!
   \internal
 */
static inline quint32 f2i(float f)
{
    quint32 i;
    memcpy(&i, &f, sizeof(f));
    return i;
}

/*!
    Returns the number of representable floating-point numbers between \a a and \a b.

    This function provides an alternative way of doing approximated comparisons of floating-point
    numbers similar to qFuzzyCompare(). However, it returns the distance between two numbers, which
    gives the caller a possibility to choose the accepted error. Errors are relative, so for
    instance the distance between 1.0E-5 and 1.00001E-5 will give 110, while the distance between
    1.0E36 and 1.00001E36 will give 127.

    This function is useful if a floating point comparison requires a certain precision.
    Therefore, if \a a and \a b are equal it will return 0. The maximum value it will return for 32-bit
    floating point numbers is 4,278,190,078. This is the distance between \c{-FLT_MAX} and
    \c{+FLT_MAX}.

    The function does not give meaningful results if any of the arguments are \c Infinite or \c NaN.
    You can check for this by calling qIsFinite().

    The return value can be considered as the "error", so if you for instance want to compare
    two 32-bit floating point numbers and all you need is an approximated 24-bit precision, you can
    use this function like this:

    \snippet code/src_corelib_global_qnumeric.cpp 0

    \sa qFuzzyCompare()
    \since 5.2
    \relates <QtNumeric>
*/
Q_CORE_EXPORT quint32 qFloatDistance(float a, float b)
{
    static const quint32 smallestPositiveFloatAsBits = 0x00000001;  // denormalized, (SMALLEST), (1.4E-45)
    /* Assumes:
       * IEE754 format.
       * Integers and floats have the same endian
    */
    static_assert(sizeof(quint32) == sizeof(float));
    Q_ASSERT(qIsFinite(a) && qIsFinite(b));
    if (a == b)
        return 0;
    if ((a < 0) != (b < 0)) {
        // if they have different signs
        if (a < 0)
            a = -a;
        else /*if (b < 0)*/
            b = -b;
        return qFloatDistance(0.0F, a) + qFloatDistance(0.0F, b);
    }
    if (a < 0) {
        a = -a;
        b = -b;
    }
    // at this point a and b should not be negative

    // 0 is special
    if (!a)
        return f2i(b) - smallestPositiveFloatAsBits + 1;
    if (!b)
        return f2i(a) - smallestPositiveFloatAsBits + 1;

    // finally do the common integer subtraction
    return a > b ? f2i(a) - f2i(b) : f2i(b) - f2i(a);
}


/*!
   \internal
 */
static inline quint64 d2i(double d)
{
    quint64 i;
    memcpy(&i, &d, sizeof(d));
    return i;
}

/*!
    Returns the number of representable floating-point numbers between \a a and \a b.

    This function serves the same purpose as \c{qFloatDistance(float, float)}, but
    returns the distance between two \c double numbers. Since the range is larger
    than for two \c float numbers (\c{[-DBL_MAX,DBL_MAX]}), the return type is quint64.


    \sa qFuzzyCompare()
    \since 5.2
    \relates <QtNumeric>
*/
Q_CORE_EXPORT quint64 qFloatDistance(double a, double b)
{
    static const quint64 smallestPositiveFloatAsBits = 0x1;  // denormalized, (SMALLEST)
    /* Assumes:
       * IEE754 format double precision
       * Integers and floats have the same endian
    */
    static_assert(sizeof(quint64) == sizeof(double));
    Q_ASSERT(qIsFinite(a) && qIsFinite(b));
    if (a == b)
        return 0;
    if ((a < 0) != (b < 0)) {
        // if they have different signs
        if (a < 0)
            a = -a;
        else /*if (b < 0)*/
            b = -b;
        return qFloatDistance(0.0, a) + qFloatDistance(0.0, b);
    }
    if (a < 0) {
        a = -a;
        b = -b;
    }
    // at this point a and b should not be negative

    // 0 is special
    if (!a)
        return d2i(b) - smallestPositiveFloatAsBits + 1;
    if (!b)
        return d2i(a) - smallestPositiveFloatAsBits + 1;

    // finally do the common integer subtraction
    return a > b ? d2i(a) - d2i(b) : d2i(b) - d2i(a);
}

/*!
    \fn template<typename T> bool qAddOverflow(T v1, T v2, T *result)
    \relates <QtNumeric>
    \since 6.1

    Adds two values \a v1 and \a v2, of a numeric type \c T and records the
    value in \a result. If the addition overflows the valid range for type \c T,
    returns \c true, otherwise returns \c false.

    An implementation is guaranteed to be available for 8-, 16-, and 32-bit
    integer types, as well as integer types of the size of a pointer. Overflow
    math for other types, if available, is considered private API.
*/

/*!
    \fn template <typename T, T V2> bool qAddOverflow(T v1, std::integral_constant<T, V2>, T *r)
    \since 6.1
    \internal

    Equivalent to qAddOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
*/

/*!
    \fn template <auto V2, typename T> bool qAddOverflow(T v1, T *r)
    \since 6.1
    \internal

    Equivalent to qAddOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
*/

/*!
    \fn template<typename T> bool qSubOverflow(T v1, T v2, T *result)
    \relates <QtNumeric>
    \since 6.1

    Subtracts \a v2 from \a v1 and records the resulting value in \a result. If
    the subtraction overflows the valid range for type \c T, returns \c true,
    otherwise returns \c false.

    An implementation is guaranteed to be available for 8-, 16-, and 32-bit
    integer types, as well as integer types of the size of a pointer. Overflow
    math for other types, if available, is considered private API.
*/

/*!
    \fn template <typename T, T V2> bool qSubOverflow(T v1, std::integral_constant<T, V2>, T *r)
    \since 6.1
    \internal

    Equivalent to qSubOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
*/

/*!
    \fn template <auto V2, typename T> bool qSubOverflow(T v1, T *r)
    \since 6.1
    \internal

    Equivalent to qSubOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
*/

/*!
    \fn template<typename T> bool qMulOverflow(T v1, T v2, T *result)
    \relates <QtNumeric>
    \since 6.1

    Multiplies \a v1 and \a v2, and records the resulting value in \a result. If
    the multiplication overflows the valid range for type \c T, returns
    \c true, otherwise returns \c false.

    An implementation is guaranteed to be available for 8-, 16-, and 32-bit
    integer types, as well as integer types of the size of a pointer. Overflow
    math for other types, if available, is considered private API.
*/

/*!
    \fn template <typename T, T V2> bool qMulOverflow(T v1, std::integral_constant<T, V2>, T *r)
    \since 6.1
    \internal

    Equivalent to qMulOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
    This can be faster than calling the version with only variable arguments.
*/

/*!
    \fn template <auto V2, typename T> bool qMulOverflow(T v1, T *r)
    \since 6.1
    \internal

    Equivalent to qMulOverflow(v1, v2, r) with \a v1 as first argument, the
    compile time constant \c V2 as second argument, and \a r as third argument.
    This can be faster than calling the version with only variable arguments.
*/

/*! \fn template <typename T> T qAbs(const T &t)
    \relates <QtNumeric>

    Compares \a t to the 0 of type T and returns the absolute
    value. Thus if T is \e {double}, then \a t is compared to
    \e{(double) 0}.

    Example:

    \snippet code/src_corelib_global_qglobal.cpp 10
*/

/*! \fn int qRound(double d)
    \relates <QtNumeric>

    Rounds \a d to the nearest integer.

    Rounds half away from zero (e.g. 0.5 -> 1, -0.5 -> -1).

    \note This function does not guarantee correctness for high precisions.

    Example:

    \snippet code/src_corelib_global_qglobal.cpp 11A

    \note If the value \a d is outside the range of \c int,
    the behavior is undefined.
*/

/*! \fn int qRound(float d)
    \relates <QtNumeric>

    Rounds \a d to the nearest integer.

    Rounds half away from zero (e.g. 0.5f -> 1, -0.5f -> -1).

    \note This function does not guarantee correctness for high precisions.

    Example:

    \snippet code/src_corelib_global_qglobal.cpp 11B

    \note If the value \a d is outside the range of \c int,
    the behavior is undefined.
*/

/*! \fn qint64 qRound64(double d)
    \relates <QtNumeric>

    Rounds \a d to the nearest 64-bit integer.

    Rounds half away from zero (e.g. 0.5 -> 1, -0.5 -> -1).

    \note This function does not guarantee correctness for high precisions.

    Example:

    \snippet code/src_corelib_global_qglobal.cpp 12A

    \note If the value \a d is outside the range of \c qint64,
    the behavior is undefined.
*/

/*! \fn qint64 qRound64(float d)
    \relates <QtNumeric>

    Rounds \a d to the nearest 64-bit integer.

    Rounds half away from zero (e.g. 0.5f -> 1, -0.5f -> -1).

    \note This function does not guarantee correctness for high precisions.

    Example:

    \snippet code/src_corelib_global_qglobal.cpp 12B

    \note If the value \a d is outside the range of \c qint64,
    the behavior is undefined.
*/

/*!
    \fn bool qFuzzyCompare(double p1, double p2)
    \relates <QtNumeric>
    \since 4.4
    \threadsafe

    Compares the floating point value \a p1 and \a p2 and
    returns \c true if they are considered equal, otherwise \c false.

    Note that comparing values where either \a p1 or \a p2 is 0.0 will not work,
    nor does comparing values where one of the values is NaN or infinity.
    If one of the values is always 0.0, use qFuzzyIsNull instead. If one of the
    values is likely to be 0.0, one solution is to add 1.0 to both values.

    \snippet code/src_corelib_global_qglobal.cpp 46

    The two numbers are compared in a relative way, where the
    exactness is stronger the smaller the numbers are.
*/

/*!
    \fn bool qFuzzyCompare(float p1, float p2)
    \relates <QtNumeric>
    \since 4.4
    \threadsafe

    Compares the floating point value \a p1 and \a p2 and
    returns \c true if they are considered equal, otherwise \c false.

    The two numbers are compared in a relative way, where the
    exactness is stronger the smaller the numbers are.
*/

/*!
    \fn bool qFuzzyIsNull(double d)
    \relates <QtNumeric>
    \since 4.4
    \threadsafe

    Returns true if the absolute value of \a d is within 0.000000000001 of 0.0.
*/

/*!
    \fn bool qFuzzyIsNull(float f)
    \relates <QtNumeric>
    \since 4.4
    \threadsafe

    Returns true if the absolute value of \a f is within 0.00001f of 0.0.
*/

namespace QtNumericTests {

template <typename T> static constexpr T max = std::numeric_limits<T>::max();
template <typename T> static constexpr T min = std::numeric_limits<T>::min();

static_assert(qt_saturate<short>(max<unsigned>) == max<short>);
static_assert(qt_saturate<int>(max<unsigned>) == max<int>);
static_assert(qt_saturate<qint64>(max<unsigned>) == qint64(max<unsigned>));

static_assert(qt_saturate<short>(max<int>) == max<short>);
static_assert(qt_saturate<unsigned>(max<int>) == unsigned(max<int>));
static_assert(qt_saturate<qint64>(max<int>) == qint64(max<int>));

static_assert(qt_saturate<short>(max<qint64>) == max<short>);
static_assert(qt_saturate<int>(max<qint64>) == max<int>);
static_assert(qt_saturate<unsigned>(max<qint64>) == max<unsigned>);
static_assert(qt_saturate<quint64>(max<qint64>) == quint64(max<qint64>));

static_assert(qt_saturate<short>(max<quint64>) == max<short>);
static_assert(qt_saturate<int>(max<quint64>) == max<int>);
static_assert(qt_saturate<unsigned>(max<quint64>) == max<unsigned>);
static_assert(qt_saturate<qint64>(max<quint64>) == max<qint64>);

static_assert(qt_saturate<short>(min<int>) == min<short>);
static_assert(qt_saturate<qint64>(min<int>) == qint64(min<int>));
static_assert(qt_saturate<unsigned>(min<int>) == 0);
static_assert(qt_saturate<quint64>(min<int>) == 0);

static_assert(qt_saturate<short>(min<qint64>) == min<short>);
static_assert(qt_saturate<int>(min<qint64>) == min<int>);
static_assert(qt_saturate<unsigned>(min<qint64>) == 0);
static_assert(qt_saturate<quint64>(min<qint64>) == 0);

} // namespace QtNumericTests

QT_END_NAMESPACE