core-math-sys 1.3.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
/* Various special tests

Copyright (c) 2023-2025 Alexei Sibidanov and Paul Zimmermann

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.
*/

/* Usage: ./check_special -t -a -10 -b 10
          ./check_special -t -p
   -t   the test is done in parallel
   -a   first boundary
   -b   second boundary
   -p   generates random numbers in the whole binary64 range
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <math.h>
#include <fenv.h>
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#include <omp.h>
#endif
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <errno.h> // always needed for strtoll call
#include <mpfr.h>
#include "function_under_test.h"

#ifndef CORE_MATH_TESTS
#define CORE_MATH_TESTS 200000000UL /* total number of tests */
#endif

double cr_function_under_test(double);
double ref_function_under_test(double);

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

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

int rnd;
int verbose = 0;
unsigned long tested = 0;

static inline double tfun(double x){
  return cr_function_under_test(x);
}

static inline double rfun(double x){
  return ref_function_under_test(x);
}

typedef union {double f; uint64_t u;} b64u64_u;

static inline uint64_t
asuint64 (double x)
{
  b64u64_u u;
  u.f = x;
  return u.u;
}

static double
asfloat64 (uint64_t n)
{
  b64u64_u u;
  u.u = n;
  return u.f;
}

double rand_arg(double s){
  int64_t r0,r1;
  r0 = rand () | (int64_t) rand () << 31;
  r1 = rand () | (int64_t) rand () << 31;
  b64u64_u o = {.u = (((r0^((uint64_t)r1<<32))&(~(0x7ffull<<52)))|(0x3ffull<<52))};
  double r = o.f-copysign(1,o.f);
  return r*s;
}

double rand_arg2(){
  int64_t r0,r1;
  b64u64_u o;
  do {
    r0 = rand () | (int64_t) rand () << 31;
    r1 = rand () | (int64_t) rand () << 31;
    o.u = r0^((uint64_t)r1<<32);
  } while((o.u<<1)>=(0x7ffull<<53));
  return o.f;
}

static int check (double x){
  b64u64_u yr = {.f = rfun(x)}, yt = {.f = tfun(x)};
#pragma omp atomic update
  tested ++;
  if (yr.u != yt.u) {
    printf("FAIL: test_fun and ref_fun differ for x=%a\n", x);
    printf("test_fun gives %a\n", yt.f);
    printf(" ref_fun gives %a\n", yr.f);
    return -1;
  }
  return 0;
}

static void check_random(int seed, double a, double b, int64_t ntests){
  ref_init();
  ref_fesetround(rnd);
  fesetround(rnd1[rnd]);
  if (verbose)
    printf("seed = %d\n",seed);
  srand(seed);
  int fail = 0, maxfail = 10;
  double s = (b - a)*0.5, m = (a+b)*0.5;
  int64_t count = 0;
  while(1){
    int64_t i = 0, n = 10*1000;
    for(;i<n;i++){
      double x = m + rand_arg(s);
      if(check(x)) fail++;
      if(fail>=maxfail) break;
    }
    count += i;
    if (verbose)
      printf("failure(s) %d, total %"PRIx64"\n",fail,count);
    if(count>=ntests) break;
    if(fail>=maxfail) break;
  }
  if (verbose)
    printf("%d fails per %"PRIx64" calls or %.1e %%\n",
           fail, count, (double)fail/count*100);
}

static void call_random(int seed, int64_t n, double a, double b){
  fesetround(rnd1[rnd]);
  srand(seed);
  double s = (b - a)*0.5, m = (a+b)*0.5;
  for(int64_t j=0;j<n;j++){
    double x = m + rand_arg(s);
    tfun(x);
  }
}

// put in h+l a double-double approximation of atanh(x)
static void
dd_atanh (double *h, double *l, double x)
{
  mpfr_t t;
  mpfr_init2 (t, 107);
  mpfr_set_d (t, x, MPFR_RNDN);
  mpfr_atanh (t, t, MPFR_RNDN);
  *h = mpfr_get_d (t, MPFR_RNDN);
  mpfr_sub_d (t, t, *h, MPFR_RNDN);
  *l = mpfr_get_d (t, MPFR_RNDN);
  mpfr_clear (t);
}

static void scan_consecutive_aux(int64_t n, double x){
  ref_init();
  ref_fesetround(rnd);
  fesetround(rnd1[rnd]);
  while (n) {
    double h, l, d, dd;
    dd_atanh (&h, &l, x);
    d = 1.0 / (1.0 - x * x); // derivative of atanh(x)
    dd = fabs(2.0 * d * x / (1.0 - x * x)); // absolute value of 2nd derivative
    int e;
    frexp (x, &e);
    /* 2^(e-1) <= |x| < 2^e thus ulp(x) = 2^(e-53) */
    d = ldexp (d, e - 53); // multiply d by ulp(x)
    dd = ldexp (dd, 2 * (e - 53)); // multiply dd by ulp(x)^2
    /* we want j^2*dd < 2^-11 ulp(h) so that the 2nd-order term
       produces an error bounded by 2^-11 ulp(h), to that MPFR
       will be called with probability about 2^-11.
       Thus approximately j^2*dd < 2^-64 h,
       or j < 2^-32 sqrt(h/dd) */
    int64_t jmax = 0x1p-32 * sqrt (h / dd);
    if (jmax > n) jmax = n; // cap to n
    if (jmax == 0) jmax = 1; // avoid infinite loop
#define JMAX 100000000
    if (jmax > JMAX) jmax = JMAX;
    // the Taylor expansion with explicit remainder an error term j^2*dd/2
    double eps = (double) jmax * (double) jmax * 0.5 * dd;
    /* add the error term from h+l, which is bounded by
       ulp_107(h) <= 2^-106 |h| */
    eps += 0x1p-106 * fabs (h);
    /* add the error term from j*d, which is bounded by
       jmax*ulp(d) <= jmax * 2^-52 |d| */
    eps += (double) jmax * 0x1p-52 * fabs (d);
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for
#endif
    for(int64_t j=0;j<jmax;j++){
      b64u64_u v = {.f = x};
      v.u += j;
      double t = tfun (v.f);
      /* atanh(x+j*u) is approximated by h + l + j*d,
         we compute lower and upper bounds taking into
         account the maximal error 'eps' */
      double low = __builtin_fma (j, d, l);
      double wl = h + (low - eps);
      double wu = h + (low + eps);
      if (wl != wu || t != wl) // expensive test
        check(v.f);
    }
    n -= jmax;
    x += jmax * ldexp (1.0, e - 53);
  }
}

static void scan_consecutive (int64_t n, double x){
  int nthreads = 1;
  if (n < 0) {
    n = -n;
    x = asfloat64 (asuint64 (x) - n);
  }
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel
  nthreads = omp_get_num_threads ();
#endif
  int64_t h = (n - 1) / nthreads + 1; // ceil(n/nthreads)
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for schedule(static,1)
#endif
  for (int i = 0; i < nthreads; i++) {
    int64_t ni = i * h;
    double xi = asfloat64 (asuint64 (x) + ni);
    int64_t hi = (ni + h > n) ? n - ni : h;
    scan_consecutive_aux (hi, xi);
  }
  printf ("checked %lu values, expensive checks %lu\n",
          (unsigned long) n, tested);
}

static void check_val(double x){
  ref_init();
  ref_fesetround(rnd);
  fesetround(rnd1[rnd]);
  check(x);
}

static void check_random_all(int seed, double a, double b){
  int nthreads = 1;
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel
  nthreads = omp_get_num_threads();
#endif
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for
#endif
  for(int i = 0; i < nthreads; i++)
    check_random(seed + i, a, b, CORE_MATH_TESTS / nthreads);
}

static void check_random_p(int seed, int64_t ntests){
  ref_init();
  ref_fesetround(rnd);
  fesetround(rnd1[rnd]);
  if (verbose)
    printf("seed = %d\n",seed);
  srand(seed);
  int fail = 0, maxfail = 10;
  int64_t count = 0;
  while(1){
    int64_t i = 0, n = 10*1000;
    for(;i<n;i++){
      double x = rand_arg2();
      if(check(x)) fail++;
      if(fail>=maxfail) break;
    }
    count += i;
    if (verbose)
      printf("failure(s) %d, total %"PRIx64"\n",fail,count);
    if(count>=ntests) break;
    if(fail>=maxfail) break;
  }
  if (verbose)
    printf("%d fails per %"PRIx64" calls or %.1e %%\n",
           fail, count, (double)fail/count*100);
}

static void check_random_all_p(int seed){
  int nthreads = 1;
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel
  nthreads = omp_get_num_threads();
#endif
#if (defined(_OPENMP) && !defined(CORE_MATH_NO_OPENMP))
#pragma omp parallel for
#endif
  for(int i = 0; i < nthreads; i++)
    check_random_p(seed + i, CORE_MATH_TESTS / nthreads);
}

int64_t parselong(const char *str){
  char *endptr;
  errno = 0;    /* To distinguish success/failure after call */
  int64_t val = strtoll(str, &endptr, 0);
  /* Check for various possible errors. */
  if(errno != 0) {
    perror("strtol");
    exit(EXIT_FAILURE);
  }
  if(endptr == str) {
    fprintf(stderr, "No digits were found\n");
    exit(EXIT_FAILURE);
  }
  return val;
}

int main(int argc, char *argv[]){
  static struct option opts[] = {
    { "rndn",        no_argument, 0, 'n'},
    { "rndz",        no_argument, 0, 'z'},
    { "rndu",        no_argument, 0, 'u'},
    { "rndd",        no_argument, 0, 'd'},
    { "help",        no_argument, 0, 'h'},
    {"verbose",      no_argument, 0, 'v'},
    {"thread",       no_argument, 0, 't'},
    {   "exp",       no_argument, 0, 'p'},
    { "seed",  required_argument, 0, 's'},
    {"darts",  required_argument, 0, 'D'},
    {"conseq", required_argument, 0, 'C'},
    {  "rnd",  required_argument, 0, 'r'},
    {"input",  required_argument, 0, 'i'},
    {      0,                  0, 0,  0 }
  };
  // for atanh, p=1 makes little sense since the domain is (-1,1)
  int thread = 1, seed = getpid (), darts = 0, conseq = 0, p = 0;
  double x = __builtin_nan(""), a = -1, b = 1;
  int64_t n = 10*1000;
  while(1) {
    int ind = 0, c = getopt_long(argc, argv, "nudzhvtps:D:C:r:i:x:a:b:", opts, &ind);
    if(c == -1) break;
    switch(c) {
    case 'a': a = strtod(optarg,NULL); break;
    case 'b': b = strtod(optarg,NULL); break;
    case 'n': rnd = 0; break;
    case 'z': rnd = 1; break;
    case 'u': rnd = 2; break;
    case 'd': rnd = 3; break;
    case 'v': verbose = 1; break;
    case 't': thread = 1; break;
    case 'p': p = 1; break;
    case 's': seed = parselong(optarg); break;
    case 'D': darts = 1; n = parselong(optarg); break;
    case 'C': conseq = 1; n = parselong(optarg); break;
    case 'r': rnd = parselong(optarg);
      if(rnd<0||rnd>3) {
        fprintf(stderr, "Rounding mode %d is outside of the range [0,3].\n",rnd);
        exit(EXIT_FAILURE);
      }
      break;
    case 'i':
      break;
    case 'h': /* print a help message (to be written) */  break;
    case 'x': x = strtod(optarg, NULL);
      break;
    default:
      break;
    }
  }

  if(x==x){
    check_val(x);
  } else {
    if(darts){
      call_random(seed, n, a, b);
    } else if(conseq){
      scan_consecutive(n, a);
    } else {
      if(p){
	if(thread)
	  check_random_all_p(seed);
	else
	  check_random_p(seed, CORE_MATH_TESTS);
      } else {
	if(thread)
	  check_random_all(seed, a, b);
	else
	  check_random(seed, a, b, CORE_MATH_TESTS);
      }
    }
  }
  return 0;
}