core-math-sys 1.4.0

Generate bindings to CORE-MATH
Documentation
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
/* Generate special cases for sinq testing.

Copyright (c) 2026 Chen-Pang He <jdh863@gmail.com>

This file is part of the CORE-MATH project
(https://core-math.gitlabpages.inria.fr/).

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 <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <fenv.h>
#include <math.h>
#include <unistd.h>
#include <quadmath.h>
#ifdef CORE_MATH_SUPPORT_ERRNO
#include <errno.h>
#endif
#ifndef MPFR_WANT_FLOAT128
#define MPFR_WANT_FLOAT128
#endif
#include <mpfr.h>
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#include <omp.h>
#endif

typedef unsigned __int128 u128;

typedef union {
  u128 a;
  __float128 f;
} b128u128_u;

int ref_fesetround(int);
void ref_init(void);

__float128 cr_sinq(__float128);
__float128 ref_sinq(__float128);

int rnd1[] = { FE_TONEAREST, FE_TOWARDZERO, FE_UPWARD, FE_DOWNWARD };

int rnd = 0;
int verbose = 0;

#define MAX_THREADS 192

static unsigned int Seed[MAX_THREADS];

#ifndef CORE_MATH_TESTS
/* total number of tests (mpfr_sin is slow for huge exponents) */
#define CORE_MATH_TESTS (100UL*1000*1000)
#endif

/* define our own is_nan function to avoid depending from math.h */
static inline int is_nan(__float128 x){
  b128u128_u u = {.f = x};
  return (u.a<<1)>((u128)0x7fff<<113);
}

/* when x is a NaN, returns 1 if x is an sNaN and 0 if it is a qNaN */
static inline int is_signaling(__float128 x){
  b128u128_u u = {.f = x};
  return !(u.a & ((u128)1<<111));
}

static inline int is_equal(__float128 x, __float128 y){
  if(is_nan(x)) return is_nan(y);
  if(is_nan(y)) return is_nan(x);
  b128u128_u ux = {.f = x}, uy = {.f = y};
  return ux.a == uy.a;
}

/* We have to write some special code to print errors since:
   (1) the printf hook for quadmath is not installed everywhere,
       thus printf ("%Qa", ...) does not work everywhere
   (2) quadmath_snprintf can only print a single quad,
       but quadmath_snprintf (..., "x=%Qa", x) does not work
*/
static void
error2 (__float128 x, __float128 y, __float128 z)
{
  char buf[256];
  int n;
  n = snprintf (buf, sizeof buf, "FAIL x=");
  n += quadmath_snprintf (buf + n, sizeof buf - n, "%Qa", x);
  n += snprintf (buf + n, sizeof buf - n, " ref=");
  n += quadmath_snprintf (buf + n, sizeof buf - n, "%Qa", y);
  n += snprintf (buf + n, sizeof buf - n, " z=");
  n += quadmath_snprintf (buf + n, sizeof buf - n, "%Qa", z);
  printf ("%s\n", buf);
}

/* print "FAIL <err> for x=<x> (y=<y>)", with the bit patterns of x and y
   since %Qa does not show the payload of a NaN */
static void
error (const char *err, __float128 x, __float128 y)
{
  b128u128_u ux = {.f = x}, uy = {.f = y};
  char buf[256];
  int n;
  n = snprintf (buf, sizeof buf, "FAIL %s for x=", err);
  n += quadmath_snprintf (buf + n, sizeof buf - n, "%Qa", x);
  n += snprintf (buf + n, sizeof buf - n, " [0x%016" PRIx64 "%016" PRIx64
                 "] (y=", (uint64_t) (ux.a >> 64), (uint64_t) ux.a);
  n += quadmath_snprintf (buf + n, sizeof buf - n, "%Qa", y);
  n += snprintf (buf + n, sizeof buf - n, " [0x%016" PRIx64 "%016" PRIx64
                 "])", (uint64_t) (uy.a >> 64), (uint64_t) uy.a);
  printf ("%s\n", buf);
  fflush (stdout);
}

static void check(__float128 x){
  ref_init();
  ref_fesetround(rnd);
  __float128 y1 = ref_sinq(x), y2 = cr_sinq(x);
  if(!is_equal(y1, y2)) {
    error2 (x, y1, y2);
    fflush(stdout);
#ifndef DO_NOT_ABORT
    exit (1);
#endif
  }
}

/* check that cr_sinq(x) is a qNaN, that the invalid exception is raised
   iff expect_invalid, and (with CORE_MATH_SUPPORT_ERRNO) that errno is set
   to EDOM iff expect_edom, and left unchanged otherwise */
static void
check_nan (__float128 x, int expect_invalid, int expect_edom)
{
  (void) expect_edom; /* only used with CORE_MATH_SUPPORT_ERRNO */
  feclearexcept (FE_ALL_EXCEPT);
#ifdef CORE_MATH_SUPPORT_ERRNO
  errno = 0;
#endif
  __float128 y = cr_sinq (x);
  if (!is_nan (y))
    error ("sinq(x) should be NaN", x, y);
  else if (is_signaling (y))
    error ("sinq(x) should be a qNaN", x, y);
  else if (expect_invalid && !fetestexcept (FE_INVALID))
    error ("Missing invalid exception", x, y);
  else if (!expect_invalid && fetestexcept (FE_INVALID))
    error ("Spurious invalid exception", x, y);
#ifdef CORE_MATH_SUPPORT_ERRNO
  else if (expect_edom && errno != EDOM)
    error ("Missing errno=EDOM", x, y);
  else if (!expect_edom && errno != 0)
    error ("Spurious errno", x, y);
#endif
  else
    return;
#ifndef DO_NOT_ABORT
  exit (1);
#endif
}

/* check that cr_sinq(x) equals expected bit-for-bit, raises no exception
   (in particular no inexact exception), and (with CORE_MATH_SUPPORT_ERRNO)
   leaves errno unchanged */
static void
check_exact (__float128 x, __float128 expected)
{
  feclearexcept (FE_ALL_EXCEPT);
#ifdef CORE_MATH_SUPPORT_ERRNO
  errno = 0;
#endif
  __float128 y = cr_sinq (x);
  b128u128_u uy = {.f = y}, ue = {.f = expected};
  if (uy.a != ue.a)
    error2 (x, expected, y);
  else if (fetestexcept (FE_INEXACT))
    error ("Spurious inexact exception", x, y);
  else if (fetestexcept (FE_ALL_EXCEPT))
    error ("Spurious exception", x, y);
#ifdef CORE_MATH_SUPPORT_ERRNO
  else if (errno != 0)
    error ("Spurious errno", x, y);
#endif
  else
    return;
#ifndef DO_NOT_ABORT
  exit (1);
#endif
}

static void
check_invalid (void)
{
  b128u128_u plus_inf = {.a = (u128) 0x7fff << 112};
  b128u128_u minus_inf = {.a = (u128) 0xffff << 112};
  b128u128_u plus_qnan = {.a = ((u128) 0x7fff << 112) | ((u128) 1 << 111)};
  b128u128_u minus_qnan = {.a = ((u128) 0xffff << 112) | ((u128) 1 << 111)};
  b128u128_u plus_snan = {.a = ((u128) 0x7fff << 112) | 1};
  b128u128_u minus_snan = {.a = ((u128) 0xffff << 112) | 1};
  b128u128_u plus_zero = {.a = 0};
  b128u128_u minus_zero = {.a = (u128) 1 << 127};

  /* sinq(+/-Inf) = NaN with invalid exception and errno=EDOM */
  check_nan (plus_inf.f, 1, 1);
  check_nan (minus_inf.f, 1, 1);
  /* sinq(qNaN) = qNaN with no exception (and errno unchanged) */
  check_nan (plus_qnan.f, 0, 0);
  check_nan (minus_qnan.f, 0, 0);
  /* sinq(sNaN) = qNaN with invalid exception (and errno unchanged) */
  check_nan (plus_snan.f, 1, 0);
  check_nan (minus_snan.f, 1, 0);
  /* sinq(+0) = +0 and sinq(-0) = -0 exactly, with no exception */
  check_exact (plus_zero.f, plus_zero.f);
  check_exact (minus_zero.f, minus_zero.f);
}

/* random 64-bit value from three rand_r() calls (31 random bits each) */
static uint64_t rand64(int tid){
  uint64_t r = rand_r(Seed + tid);
  r = (r << 31) | rand_r(Seed + tid);
  r = (r << 2) | (rand_r(Seed + tid) & 3);
  return r;
}

static u128 rand128(int tid){
  u128 r = rand64(tid);
  return (r << 64) | rand64(tid);
}

/* Compare tiny inputs against MPFR, including tininess after rounding.
   Unlike expq, sinq needs inputs near zero, not logarithms of the limits.
   The normal/subnormal boundary is tested too: directed rounding can make
   sinq(+/-2^-16382) subnormal. */
static void
check_tiny (__float128 x)
{
  ref_init();
  ref_fesetround(rnd);
  mpfr_clear_flags();
  __float128 expected = ref_sinq(x);
  int inexact = !!mpfr_inexflag_p();
  int underflow = inexact && mpfr_underflow_p();
  int expected_flags = (inexact ? FE_INEXACT : 0)
                     | (underflow ? FE_UNDERFLOW : 0);
  feclearexcept(FE_ALL_EXCEPT);
#ifdef CORE_MATH_SUPPORT_ERRNO
  errno = 0;
#endif
  __float128 actual = cr_sinq(x);
  if (!is_equal(expected, actual))
    error2(x, expected, actual);
  else if (fetestexcept(FE_ALL_EXCEPT) != expected_flags)
    error("Incorrect exception flags for tiny input", x, actual);
#ifdef CORE_MATH_SUPPORT_ERRNO
  else if (errno != (underflow ? ERANGE : 0))
    error("Incorrect errno for tiny input", x, actual);
#endif
  else
    return;
#ifndef DO_NOT_ABORT
  exit(1);
#endif
}

static void
check_subnormal (void)
{
  /* Every significand bit boundary, including zero, the smallest
     subnormal, the largest subnormal, and the first normal values. */
  for (int bit = 0; bit <= 112; bit++)
    for (int offset = -2; offset <= 2; offset++) {
      __int128 m = ((__int128) 1 << bit) + offset;
      if (m < 0) continue;
      b128u128_u v = {.a = (u128) m};
      check_tiny(v.f);
      v.a |= (u128) 1 << 127;
      check_tiny(v.f);
    }

  /* Uniform nonzero subnormal significands, with both signs. */
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for
#endif
  for (uint64_t n = 0; n < CORE_MATH_TESTS / 10; n++) {
    int tid = 0;
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
    tid = omp_get_thread_num();
#endif
    u128 m = rand128(tid) & (((u128) 1 << 112) - 1);
    if (m == 0) m = 1;
    b128u128_u v = {.a = m};
    check_tiny(v.f);
    v.a |= (u128) 1 << 127;
    check_tiny(v.f);
  }
}

/* random bit pattern (with random sign): this covers all exponents,
   including subnormals, Inf and NaN */
static __float128 get_random(int tid){
  b128u128_u v = {.a = rand128(tid)};
  return v.f;
}

/* random significand and sign, with unbiased exponent uniform in [-60,20]
   (the small-argument and argument-reduction bands) */
static __float128 get_random_banded(int tid){
  b128u128_u v = {.a = rand128(tid)};
  int e = -60 + (int) (rand_r(Seed + tid) % 81);
  v.a &= ~((u128) 0x7fff << 112);
  v.a |= (u128) (e + 16383) << 112;
  return v.f;
}

/* return k*pi/2 rounded to binary128, where k is a random integer with a
   random bit-length, perturbed by -3..+3 ulps, with a random sign: this
   exercises the cancellation in the argument reduction near multiples of
   pi/2. Half of the draws take k < 2^112, where the rounding error of x is
   much smaller than pi/2 (thus x is really within a few ulps of a multiple
   of pi/2); the other half spread the bit-length over [1,16388], which
   covers all binades up to the overflow threshold. */
static __float128 get_random_near_pio2(int tid){
  unsigned long nbits = (rand_r(Seed + tid) & 1)
    ? 1 + rand_r(Seed + tid) % 112
    : 1 + rand_r(Seed + tid) % (16383 + 5);
  unsigned long chunks = (nbits + 63) / 64;
  unsigned long top = nbits - 64 * (chunks - 1); /* bits in the top chunk */
  /* k*pi/2 can exceed the binary128 range: widen the MPFR exponent range
     for this computation (check() restores it through ref_init()) */
  mpfr_exp_t emax = mpfr_get_emax ();
  mpfr_set_emax (mpfr_get_emax_max ());
  mpfr_t k, p;
  mpfr_init2 (k, nbits);
  mpfr_set_ui (k, 0, MPFR_RNDN);
  for (unsigned long i = 0; i < chunks; i++) {
    uint64_t c = rand64 (tid);
    if (i == 0) {
      if (top < 64)
        c &= ((uint64_t) 1 << top) - 1;
      c |= (uint64_t) 1 << (top - 1); /* force the bit-length of k */
    }
    /* k = 2^64*k + c, exact since k has nbits bits of precision */
    mpfr_mul_2ui (k, k, 32, MPFR_RNDN);
    mpfr_add_ui (k, k, (unsigned long) (c >> 32), MPFR_RNDN);
    mpfr_mul_2ui (k, k, 32, MPFR_RNDN);
    mpfr_add_ui (k, k, (unsigned long) (c & 0xffffffff), MPFR_RNDN);
  }
  mpfr_init2 (p, nbits + 130);
  mpfr_const_pi (p, MPFR_RNDN);
  mpfr_mul (p, p, k, MPFR_RNDN);
  mpfr_div_2ui (p, p, 1, MPFR_RNDN);
  b128u128_u v;
  if (mpfr_get_exp (p) > 16384) /* k*pi/2 >= 2^16384 overflows */
    v.a = (u128) 0x7fff << 112;
  else
    v.f = mpfr_get_float128 (p, MPFR_RNDN);
  mpfr_clear (k);
  mpfr_clear (p);
  mpfr_set_emax (emax);
  /* perturb by -3..+3 ulps (p > 0 thus v.f > 0, and the bit pattern of a
     positive binary128 is monotonic in its value) */
  v.a += (u128) (__int128) ((int) (rand_r (Seed + tid) % 7) - 3);
  /* random sign */
  if (rand_r (Seed + tid) & 1)
    v.a ^= (u128) 1 << 127;
  return v.f;
}

static void
check_random (__float128 (*get)(int))
{
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for
#endif
  for(uint64_t n = 0; n < CORE_MATH_TESTS / 3; n++){
    ref_init();
    ref_fesetround(rnd);
    int tid;
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
    tid = omp_get_thread_num();
#else
    tid = 0;
#endif
    __float128 x = get(tid);
    check(x);
  }
}

int main(int argc, char *argv[]){
  while(argc >= 2){
    if(strcmp(argv[1], "--rndn") == 0){
      rnd = 0;
      argc --;
      argv ++;
    } else if(strcmp(argv[1], "--rndz") == 0){
      rnd = 1;
      argc --;
      argv ++;
    } else if(strcmp(argv[1], "--rndu") == 0){
      rnd = 2;
      argc --;
      argv ++;
    } else if(strcmp(argv[1], "--rndd") == 0){
      rnd = 3;
      argc --;
      argv ++;
    } else if(strcmp(argv[1], "--verbose") == 0){
      verbose = 1;
      argc --;
      argv ++;
    } else {
      fprintf(stderr, "Error, unknown option %s\n", argv[1]);
      exit(1);
    }
  }

  ref_init();
  ref_fesetround(rnd);
  fesetround(rnd1[rnd]);

  unsigned int seed = getpid();
  for(int i = 0; i < MAX_THREADS; i++)
    Seed[i] = seed + i;

  printf("Checking special values\n");
  check_invalid ();

  printf("Checking subnormal inputs and the normal boundary\n");
  check_subnormal ();

  printf("Checking random values in the full range\n");
  check_random (get_random);

  printf("Checking random values with exponent in [-60,20]\n");
  check_random (get_random_banded);

  printf("Checking random values near multiples of pi/2\n");
  check_random (get_random_near_pio2);

  return 0;
}