Coverage Report

Created: 2026-11-30 07:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/r-source/src/main/complex.c
Line
Count
Source
1
/*
2
 *  R : A Computer Language for Statistical Data Analysis
3
 *  Copyright (C) 2000-2025  The R Core Team
4
 *  Copyright (C) 2005       The R Foundation
5
 *  Copyright (C) 1995-1997  Robert Gentleman and Ross Ihaka
6
 *
7
 *  This program is free software; you can redistribute it and/or modify
8
 *  it under the terms of the GNU General Public License as published by
9
 *  the Free Software Foundation; either version 2 of the License, or
10
 *  (at your option) any later version.
11
 *
12
 *  This program is distributed in the hope that it will be useful,
13
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 *  GNU General Public License for more details.
16
 *
17
 *  You should have received a copy of the GNU General Public License
18
 *  along with this program; if not, a copy is available at
19
 *  https://www.R-project.org/Licenses/
20
 */
21
22
#ifdef HAVE_CONFIG_H
23
#include <config.h>
24
#endif
25
26
/* Note: gcc -pedantic may warn in several places about C99 features
27
   as extensions.
28
   This was a very-long-standing GCC bug, http://gcc.gnu.org/PR7263
29
   The system <complex.h> header can work around it: some do.
30
   It should have been resolved (after a decade) in 2012.
31
*/
32
33
#if defined(HAVE_CTANH) && !defined(HAVE_WORKING_CTANH)
34
#undef HAVE_CTANH
35
#endif
36
37
#if 0
38
/* For testing substitute fns */
39
#undef HAVE_CARG
40
#undef HAVE_CABS
41
#undef HAVE_CPOW
42
#undef HAVE_CEXP
43
#undef HAVE_CLOG
44
#undef HAVE_CSQRT
45
#undef HAVE_CSIN
46
#undef HAVE_CCOS
47
#undef HAVE_CTAN
48
#undef HAVE_CASIN
49
#undef HAVE_CACOS
50
#undef HAVE_CATAN
51
#undef HAVE_CSINH
52
#undef HAVE_CCOSH
53
#undef HAVE_CTANH
54
#endif
55
56
#ifdef __SUNPRO_C
57
/* segfaults in Solaris Studio 12.3 */
58
#undef HAVE_CPOW
59
#endif
60
61
#include <Defn.h>   /* -> ../include/R_ext/Complex.h */
62
#include <Internal.h>
63
#include <Rmath.h>
64
65
#include "arithmetic.h"   /* complex_*  */
66
#include <complex.h>            /* incl "complex math.h" */
67
#include "Rcomplex.h"   /* I, SET_C99_COMPLEX, toC99 */
68
#include <R_ext/Itermacros.h>
69
70
71
/* interval at which to check interrupts, a guess */
72
#define NINTERRUPT 10000000
73
74
75
attribute_hidden SEXP complex_unary(ARITHOP_TYPE code, SEXP s1, SEXP call)
76
1.26M
{
77
1.26M
    R_xlen_t i, n;
78
1.26M
    SEXP ans;
79
80
1.26M
    switch(code) {
81
32.8k
    case PLUSOP:
82
32.8k
  return s1;
83
1.22M
    case MINUSOP:
84
1.22M
  ans = NO_REFERENCES(s1) ? s1 : duplicate(s1);
85
1.22M
  Rcomplex *pans = COMPLEX(ans);
86
1.22M
  const Rcomplex *ps1 = COMPLEX_RO(s1);
87
1.22M
  n = XLENGTH(s1);
88
4.20M
  for (i = 0; i < n; i++) {
89
2.97M
      Rcomplex x = ps1[i];
90
2.97M
      pans[i].r = -x.r;
91
2.97M
      pans[i].i = -x.i;
92
2.97M
  }
93
1.22M
  return ans;
94
36
    default:
95
36
  errorcall(call, _("invalid complex unary operator"));
96
1.26M
    }
97
0
    return R_NilValue; /* -Wall */
98
1.26M
}
99
100
static R_INLINE double complex R_cpow_n(double complex X, int k)
101
16.6M
{
102
16.6M
    if(k == 0) return (double complex) 1.;
103
11.7M
    else if(k == 1) return X;
104
10.8M
    else if(k < 0) return 1. / R_cpow_n(X, -k);
105
5.16M
    else {/* k > 0 */
106
5.16M
  double complex z = (double complex) 1.;;
107
56.5M
  while (k > 0) {
108
56.5M
      if (k & 1) z = z * X;
109
56.5M
      if (k == 1) break;
110
51.4M
      k >>= 1; /* efficient division by 2; now have k >= 1 */
111
51.4M
      X = X * X;
112
51.4M
  }
113
5.16M
  return z;
114
5.16M
    }
115
16.6M
}
116
117
#if defined(Win32)
118
# undef HAVE_CPOW
119
#endif
120
/* reason for this:
121
  1) X^n  (e.g. for n = +/- 2, 3) is unnecessarily inaccurate in glibc;
122
     cut-off 65536 : guided from empirical speed measurements
123
124
  2) On Mingw (but not Mingw-w64) the system cpow is explicitly linked
125
     against the (slow) MSVCRT pow, and gets (0+0i)^Y as 0+0i for all Y.
126
127
  3) PPC macOS crashed on powers of 0+0i (at least under Rosetta).
128
  Really 0i^-1 should by Inf+NaNi, but getting that portably seems too hard.
129
  (C1x's CMPLX will eventually be possible.)
130
*/
131
132
static double complex mycpow (double complex X, double complex Y)
133
15.2M
{
134
15.2M
    double complex Z;
135
15.2M
    double yr = creal(Y), yi = cimag(Y);
136
15.2M
    int k;
137
15.2M
    if (X == 0.0) {
138
2.12M
  if (yi == 0.0) Z = R_pow(0.0, yr); else Z = R_NaN + R_NaN*I;
139
13.1M
    } else if (yi == 0.0 && yr == (k = (int) yr) && abs(k) <= 65536)
140
10.9M
  Z = R_cpow_n(X, k);
141
2.13M
    else
142
2.13M
#ifdef HAVE_CPOW
143
2.13M
  Z = cpow(X, Y);
144
#else
145
    {
146
  /* Used for FreeBSD and MingGW, hence mainly with gcc */
147
  double rho, r, i, theta;
148
  r = hypot(creal(X), cimag(X));
149
  i = atan2(cimag(X), creal(X));
150
  theta = i * yr;
151
  if (yi == 0.0)
152
      rho = pow(r, yr);
153
  else {
154
      /* rearrangement of cexp(X * clog(Y)) */
155
      r = log(r);
156
      theta += r * yi;
157
      rho = exp(r * yr - i * yi);
158
  }
159
#ifdef __GNUC__
160
  __real__ Z = rho * cos(theta);
161
  __imag__ Z = rho * sin(theta);
162
#else
163
  Z = rho * cos(theta) + (rho * sin(theta)) * I;
164
#endif
165
    }
166
#endif
167
15.2M
    return Z;
168
15.2M
}
169
170
171
172
attribute_hidden SEXP complex_binary(ARITHOP_TYPE code, SEXP s1, SEXP s2)
173
3.53M
{
174
3.53M
    R_xlen_t i, i1, i2, n, n1, n2;
175
3.53M
    SEXP ans;
176
177
    /* Note: "s1" and "s2" are protected in the calling code. */
178
3.53M
    n1 = XLENGTH(s1);
179
3.53M
    n2 = XLENGTH(s2);
180
     /* S4-compatibility change: if n1 or n2 is 0, result is of length 0 */
181
3.53M
    if (n1 == 0 || n2 == 0) return(allocVector(CPLXSXP, 0));
182
183
3.31M
    n = (n1 > n2) ? n1 : n2;
184
3.31M
    ans = R_allocOrReuseVector(s1, s2, CPLXSXP, n);
185
3.31M
    PROTECT(ans);
186
187
3.31M
    Rcomplex *pans = COMPLEX(ans);
188
3.31M
    const Rcomplex *ps1 = COMPLEX_RO(s1);
189
3.31M
    const Rcomplex *ps2 = COMPLEX_RO(s2);
190
191
3.31M
    switch (code) {
192
71.0k
    case PLUSOP:
193
71.0k
  MOD_ITERATE2_CHECK(NINTERRUPT, n, n1, n2, i, i1, i2, {
194
71.0k
      Rcomplex x1 = ps1[i1];
195
71.0k
      Rcomplex x2 = ps2[i2];
196
71.0k
      pans[i].r = x1.r + x2.r;
197
71.0k
      pans[i].i = x1.i + x2.i;
198
71.0k
  });
199
71.0k
  break;
200
1.38M
    case MINUSOP:
201
1.38M
  MOD_ITERATE2_CHECK(NINTERRUPT, n, n1, n2, i, i1, i2, {
202
1.38M
      Rcomplex x1 = ps1[i1];
203
1.38M
      Rcomplex x2 = ps2[i2];
204
1.38M
      pans[i].r = x1.r - x2.r;
205
1.38M
      pans[i].i = x1.i - x2.i;
206
1.38M
  });
207
1.38M
  break;
208
915k
    case TIMESOP:
209
915k
  MOD_ITERATE2_CHECK(NINTERRUPT, n, n1, n2, i, i1, i2, {
210
915k
      SET_C99_COMPLEX(pans, i,
211
915k
          toC99(&ps1[i1]) * toC99(&ps2[i2]));
212
915k
  });
213
915k
  break;
214
191k
    case DIVOP:
215
191k
  MOD_ITERATE2_CHECK(NINTERRUPT, n, n1, n2, i, i1, i2, {
216
191k
      SET_C99_COMPLEX(pans, i,
217
191k
          toC99(&ps1[i1]) / toC99(&ps2[i2]));
218
191k
  });
219
191k
  break;
220
749k
    case POWOP:
221
749k
  MOD_ITERATE2_CHECK(NINTERRUPT, n, n1, n2, i, i1, i2, {
222
749k
      SET_C99_COMPLEX(pans, i,
223
749k
          mycpow(toC99(&ps1[i1]), toC99(&ps2[i2])));
224
749k
  });
225
749k
  break;
226
82
    default:
227
82
  error(_("unimplemented complex operation"));
228
3.31M
    }
229
3.31M
    UNPROTECT(1);
230
231
    /* quick return if there are no attributes */
232
3.31M
    if (ATTRIB(s1) == R_NilValue && ATTRIB(s2) == R_NilValue)
233
2.95M
  return ans;
234
235
    /* Copy attributes from longer argument. */
236
237
356k
    if (ans != s2 && n == n2 && ATTRIB(s2) != R_NilValue)
238
2.53k
  copyMostAttrib(s2, ans);
239
356k
    if (ans != s1 && n == n1 && ATTRIB(s1) != R_NilValue)
240
7.72k
  copyMostAttrib(s1, ans); /* Done 2nd so s1's attrs overwrite s2's */
241
242
356k
    return ans;
243
3.31M
}
244
245
attribute_hidden SEXP do_cmathfuns(SEXP call, SEXP op, SEXP args, SEXP env)
246
15
{
247
15
    SEXP x, y = R_NilValue; /* -Wall*/
248
15
    R_xlen_t i, n;
249
250
15
    checkArity(op, args);
251
15
    check1arg(args, call, "z");
252
15
    if (DispatchGroup("Complex", call, op, args, env, &x))
253
0
  return x;
254
15
    x = CAR(args);
255
15
    if (isComplex(x)) {
256
13
  n = XLENGTH(x);
257
13
  const Rcomplex *px = COMPLEX_RO(x);
258
13
  switch(PRIMVAL(op)) {
259
0
  case 1: /* Re */
260
0
      {
261
0
    y = allocVector(REALSXP, n);
262
0
    double *py = REAL(y);
263
0
    for(i = 0 ; i < n ; i++)
264
0
        py[i] = px[i].r;
265
0
      }
266
0
      break;
267
0
  case 2: /* Im */
268
0
      {
269
0
    y = allocVector(REALSXP, n);
270
0
    double *py = REAL(y);
271
0
    for(i = 0 ; i < n ; i++)
272
0
        py[i] = px[i].i;
273
0
      }
274
0
      break;
275
0
  case 3: /* Mod */
276
13
  case 6: /* abs */
277
13
      {
278
13
    y = allocVector(REALSXP, n);
279
13
    double *py = REAL(y);
280
516
    for(i = 0 ; i < n ; i++)
281
503
#if HAVE_CABS
282
503
        py[i] = cabs(toC99(&px[i]));
283
#else
284
        py[i] = hypot(px[i].r, px[i].i);
285
#endif
286
13
      }
287
13
      break;
288
0
  case 4: /* Arg */
289
0
      {
290
0
    y = allocVector(REALSXP, n);
291
0
    double *py = REAL(y);
292
0
    for(i = 0 ; i < n ; i++)
293
0
#if HAVE_CARG
294
0
        py[i] = carg(toC99(&px[i]));
295
#else
296
        py[i] = atan2(px[i].i, px[i].r);
297
#endif
298
0
      }
299
0
      break;
300
0
  case 5: /* Conj */
301
0
      {
302
0
    y = NO_REFERENCES(x) ? x : allocVector(CPLXSXP, n);
303
0
    Rcomplex *py = COMPLEX(y);
304
0
    for(i = 0 ; i < n ; i++) {
305
0
        py[i].r = px[i].r;
306
0
        py[i].i = -px[i].i;
307
0
    }
308
0
      }
309
0
      break;
310
13
  }
311
13
    }
312
2
    else if(isNumeric(x)) { /* so no complex numbers involved */
313
0
  n = XLENGTH(x);
314
0
  if(isReal(x)) PROTECT(x);
315
0
  else PROTECT(x = coerceVector(x, REALSXP));
316
0
  y = NO_REFERENCES(x) ? x : allocVector(REALSXP, n);
317
0
  double *py = REAL(y);
318
0
  const double *px = REAL_RO(x);
319
320
0
  switch(PRIMVAL(op)) {
321
0
  case 1: /* Re */
322
0
  case 5: /* Conj */
323
0
      for(i = 0 ; i < n ; i++)
324
0
    py[i] = px[i];
325
0
      break;
326
0
  case 2: /* Im */
327
0
      for(i = 0 ; i < n ; i++)
328
0
    py[i] = 0.0;
329
0
      break;
330
0
  case 4: /* Arg */
331
0
      for(i = 0 ; i < n ; i++)
332
0
    if(ISNAN(px[i]))
333
0
        py[i] = px[i];
334
0
    else if (px[i] >= 0)
335
0
        py[i] = 0;
336
0
    else
337
0
        py[i] = M_PI;
338
0
      break;
339
0
  case 3: /* Mod */
340
0
  case 6: /* abs */
341
0
      for(i = 0 ; i < n ; i++)
342
0
    py[i] = fabs(px[i]);
343
0
      break;
344
0
  }
345
0
  UNPROTECT(1);
346
0
    }
347
2
    else errorcall(call, _("non-numeric argument to function"));
348
349
15
    if (x != y && ATTRIB(x) != R_NilValue) {
350
5
  PROTECT(x);
351
5
  PROTECT(y);
352
5
  SHALLOW_DUPLICATE_ATTRIB(y, x);
353
5
  UNPROTECT(2);
354
5
    }
355
15
    return y;
356
15
}
357
358
/* Implementing  signif(<complex>)  *and* used in format.c and printutils.c */
359
0
#define MAX_DIGITS 22
360
attribute_hidden void z_prec_r(Rcomplex *r, const Rcomplex *x, double digits)
361
0
{
362
    // Implement    r <- signif(x, digits)
363
364
0
    r->r = x->r; r->i = x->i;
365
0
    double m = 0.0,
366
0
  m1 = fabs(x->r),
367
0
  m2 = fabs(x->i);
368
0
    if(R_FINITE(m1)) m = m1;
369
0
    if(R_FINITE(m2) && m2 > m) m = m2;
370
0
    if (m == 0.0) return;
371
0
    if (!R_FINITE(digits)) {
372
0
  if(digits > 0) return; else {r->r = r->i = 0.0; return ;}
373
0
    }
374
0
    int dig = (int)floor(digits+0.5);
375
0
    if (dig > MAX_DIGITS) return; else if (dig < 1) dig = 1;
376
0
    int mag = (int)floor(log10(m));
377
0
    dig = dig - mag - 1;
378
0
    if (dig > 306) {
379
0
  double pow10 = 1.0e4;
380
0
  digits = (double)(dig - 4);
381
0
  r->r = fround(pow10 * x->r, digits)/pow10;
382
0
  r->i = fround(pow10 * x->i, digits)/pow10;
383
0
    } else {
384
0
  digits = (double)(dig);
385
0
  r->r = fround(x->r, digits);
386
0
  r->i = fround(x->i, digits);
387
0
    }
388
0
}
389
390
/* These substitute functions are rarely used, and not extensively
391
   tested, e.g. over CRAN.  Please do not change without very good
392
   reason!
393
394
   Currently (Feb 2011) they are used on FreeBSD.
395
*/
396
397
#ifndef HAVE_CLOG
398
#define clog R_clog
399
/* FIXME: maybe add full IEC60559 support */
400
static double complex clog(double complex x)
401
{
402
    double xr = creal(x), xi = cimag(x);
403
    return log(hypot(xr, xi)) + atan2(xi, xr)*I;
404
}
405
#endif
406
407
#ifndef HAVE_CSQRT
408
#define csqrt R_csqrt
409
/* FreeBSD does have this one */
410
static double complex csqrt(double complex x)
411
{
412
    return mycpow(x, 0.5+0.0*I);
413
}
414
#endif
415
416
#ifndef HAVE_CEXP
417
#define cexp R_cexp
418
/* FIXME: check/add full IEC60559 support */
419
static double complex cexp(double complex x)
420
{
421
    double expx = exp(creal(x)), y = cimag(x);
422
    return expx * cos(y) + (expx * sin(y)) * I;
423
}
424
#endif
425
426
#ifndef HAVE_CCOS
427
#define ccos R_ccos
428
static double complex ccos(double complex x)
429
{
430
    double xr = creal(x), xi = cimag(x);
431
    return cos(xr)*cosh(xi) - sin(xr)*sinh(xi)*I; /* A&S 4.3.56 */
432
}
433
#endif
434
435
#ifndef HAVE_CSIN
436
#define csin R_csin
437
static double complex csin(double complex x)
438
{
439
    double xr = creal(x), xi = cimag(x);
440
    return sin(xr)*cosh(xi) + cos(xr)*sinh(xi)*I; /* A&S 4.3.55 */
441
}
442
#endif
443
444
#ifndef HAVE_CTAN
445
#define ctan R_ctan
446
static double complex ctan(double complex z)
447
{
448
    /* A&S 4.3.57 */
449
    double x2, y2, den, ri;
450
    x2 = 2.0 * creal(z);
451
    y2 = 2.0 * cimag(z);
452
    den = cos(x2) + cosh(y2);
453
    /* any threshold between -log(DBL_EPSILON) and log(DBL_XMAX) will do*/
454
    if (ISNAN(y2) || fabs(y2) < 50.0) ri = sinh(y2)/den;
455
    else ri = (y2 < 0 ? -1.0 : 1.0);
456
    return sin(x2)/den + ri * I;
457
}
458
#endif
459
460
#ifndef HAVE_CASIN
461
#define casin R_casin
462
static double complex casin(double complex z)
463
{
464
    /* A&S 4.4.37 */
465
    double x = creal(z), y = cimag(z),
466
  t1 = 0.5 * hypot(x + 1, y),
467
  t2 = 0.5 * hypot(x - 1, y),
468
  alpha = t1 + t2,
469
  ri = log(alpha + sqrt(alpha*alpha - 1));
470
    /* This comes from
471
       'z_asin() is continuous from below if x >= 1
472
  and continuous from above if x <= -1.'
473
    */
474
    if(y < 0 || (y == 0 && x > 1)) ri *= -1;
475
    return asin(t1  - t2) + ri*I;
476
}
477
#endif
478
479
#ifndef HAVE_CACOS
480
#define cacos R_cacos
481
static double complex cacos(double complex z)
482
{
483
    return M_PI_2 - casin(z);
484
}
485
#endif
486
487
#ifndef HAVE_CATAN
488
#define catan R_catan
489
static double complex catan(double complex z)
490
{
491
    double x = creal(z), y = cimag(z), rr, ri;
492
    rr = 0.5 * atan2(2 * x, (1 - x * x - y * y));
493
    ri = 0.25 * log((x * x + (y + 1) * (y + 1)) /
494
        (x * x + (y - 1) * (y - 1)));
495
    return rr + ri*I;
496
}
497
#endif
498
499
#ifndef HAVE_CCOSH
500
#define ccosh R_ccosh
501
static double complex ccosh(double complex z)
502
{
503
    return ccos(z * I); /* A&S 4.5.8 */
504
}
505
#endif
506
507
#ifndef HAVE_CSINH
508
#define csinh R_csinh
509
static double complex csinh(double complex z)
510
{
511
    return -I * csin(z * I); /* A&S 4.5.7 */
512
}
513
#endif
514
515
static double complex z_tan(double complex z)
516
0
{
517
0
    double y = cimag(z);
518
0
    double complex r = ctan(z);
519
0
    if(R_FINITE(y) && fabs(y) > 25.0) {
520
  /* at this point the real part is nearly zero, and the
521
     imaginary part is one: but some OSes get the imag as NaN,
522
     and OpenBSD also the real part (it multiplies Inf/Inf by I) */
523
0
  double rr = creal(r);
524
0
  if(ISNAN(rr)) {
525
0
      double x2 = 2.0 * creal(z);
526
0
      rr = sin(x2) / (cos(x2) + cosh(2.0 * y)); /* A&S 4.3.57 */
527
0
  }
528
0
#if __GNUC__
529
0
  __real__ r = rr;
530
0
  __imag__ r = y < 0 ? -1.0 : 1.0;
531
#else
532
  r = rr + (y < 0 ? -1.0 : 1.0) * I;
533
#endif
534
0
    }
535
0
    return r;
536
0
}
537
538
#ifndef HAVE_CTANH
539
#define ctanh R_ctanh
540
static double complex ctanh(double complex z)
541
{
542
    return -I * z_tan(z * I); /* A&S 4.5.9 */
543
}
544
#endif
545
546
547
/* Don't rely on the OS at the branch cuts */
548
549
static double complex z_asin(double complex z)
550
0
{
551
0
    if(cimag(z) == 0 && fabs(creal(z)) > 1) {
552
0
  double alpha, t1, t2, x = creal(z), ri;
553
0
  t1 = 0.5 * fabs(x + 1);
554
0
  t2 = 0.5 * fabs(x - 1);
555
0
  alpha = t1 + t2;
556
0
  ri = log(alpha + sqrt(alpha*alpha - 1));
557
0
  if(x > 1) ri *= -1;
558
0
  return asin(t1  - t2) + ri*I;
559
0
    }
560
0
    return casin(z);
561
0
}
562
563
static double complex z_acos(double complex z)
564
0
{
565
0
    if(cimag(z) == 0 && fabs(creal(z)) > 1) return M_PI_2 - z_asin(z);
566
0
    return cacos(z);
567
0
}
568
569
static double complex z_atan(double complex z)
570
0
{
571
0
    if(creal(z) == 0 && fabs(cimag(z)) > 1) {
572
0
  double y = cimag(z), rr, ri;
573
0
  rr = (y > 0) ? M_PI_2 : -M_PI_2;
574
0
  ri = 0.25 * log(((y + 1) * (y + 1))/((y - 1) * (y - 1)));
575
0
  return rr + ri*I;
576
0
    }
577
0
    return catan(z);
578
0
}
579
580
static double complex z_acosh(double complex z)
581
0
{
582
0
    return z_acos(z) * I;
583
0
}
584
585
static double complex z_asinh(double complex z)
586
0
{
587
0
    return -I * z_asin(z * I);
588
0
}
589
590
static double complex z_atanh(double complex z)
591
0
{
592
0
    return -I * z_atan(z * I);
593
0
}
594
595
#ifdef HAVE_CABS
596
# define R_CABS(Z) cabs(Z)
597
#else
598
# define R_CABS(Z) hypot(creal(Z), cimag(Z))
599
#endif
600
601
602
static bool cmath1(double complex (*f)(double complex),
603
           const Rcomplex *x, Rcomplex *y, R_xlen_t n)
604
561
{
605
561
    R_xlen_t i;
606
561
    bool naflag = false;
607
32.9k
    for (i = 0 ; i < n ; i++) {
608
32.3k
  if (ISNA(x[i].r) || ISNA(x[i].i)) {
609
5.28k
      y[i].r = NA_REAL; y[i].i = NA_REAL;
610
27.0k
  } else {
611
27.0k
      SET_C99_COMPLEX(y, i, f(toC99(x + i)));
612
27.0k
      if ( (ISNAN(y[i].r) || ISNAN(y[i].i)) &&
613
12.4k
    !(ISNAN(x[i].r) || ISNAN(x[i].i)) ) naflag = true;
614
27.0k
  }
615
32.3k
    }
616
561
    return naflag;
617
561
}
618
619
attribute_hidden SEXP complex_math1(SEXP call, SEXP op, SEXP args, SEXP env)
620
561
{
621
561
    SEXP x, y;
622
561
    R_xlen_t n;
623
561
    bool naflag = false;
624
625
561
    PROTECT(x = CAR(args));
626
561
    n = XLENGTH(x);
627
561
    PROTECT(y = allocVector(CPLXSXP, n));
628
629
561
    const Rcomplex *px = COMPLEX_RO(x);
630
561
    Rcomplex *py = COMPLEX(y);
631
632
561
    switch (PRIMVAL(op)) {
633
69
    case 10003: naflag = cmath1(clog, px, py, n); break;
634
  // 1: floor
635
  // 2: ceil[ing]
636
144
    case 3: naflag = cmath1(csqrt, px, py, n); break;
637
  // 4: sign
638
206
    case 10: naflag = cmath1(cexp, px, py, n); break;
639
  // 11: expm1
640
  // 12: log1p
641
52
    case 20: naflag = cmath1(ccos, px, py, n); break;
642
90
    case 21: naflag = cmath1(csin, px, py, n); break;
643
0
    case 22: naflag = cmath1(z_tan, px, py, n); break;
644
0
    case 23: naflag = cmath1(z_acos, px, py, n); break;
645
0
    case 24: naflag = cmath1(z_asin, px, py, n); break;
646
0
    case 25: naflag = cmath1(z_atan, px, py, n); break;
647
648
0
    case 30: naflag = cmath1(ccosh, px, py, n); break;
649
0
    case 31: naflag = cmath1(csinh, px, py, n); break;
650
0
    case 32: naflag = cmath1(ctanh, px, py, n); break;
651
0
    case 33: naflag = cmath1(z_acosh, px, py, n); break;
652
0
    case 34: naflag = cmath1(z_asinh, px, py, n); break;
653
0
    case 35: naflag = cmath1(z_atanh, px, py, n); break;
654
655
0
    default:
656
  /* such as sign, gamma */
657
0
  errorcall(call, _("unimplemented complex function"));
658
561
    }
659
561
    if (naflag)
660
39
  warningcall(call, "NaNs produced in function \"%s\"", PRIMNAME(op));
661
561
    SHALLOW_DUPLICATE_ATTRIB(y, x);
662
561
    UNPROTECT(2);
663
561
    return y;
664
561
}
665
666
static void z_rround(Rcomplex *r, Rcomplex *x, Rcomplex *p)
667
0
{
668
0
    r->r = fround(x->r, p->r);
669
0
    r->i = fround(x->i, p->r);
670
0
}
671
672
static void z_prec(Rcomplex *r, Rcomplex *x, Rcomplex *p)
673
0
{
674
0
    z_prec_r(r, x, p->r);
675
0
}
676
677
static void z_logbase(Rcomplex *r, Rcomplex *z, Rcomplex *base)
678
7.29k
{
679
7.29k
    double complex dz = toC99(z), dbase = toC99(base);
680
7.29k
    SET_C99_COMPLEX(r, 0, clog(dz)/clog(dbase));
681
7.29k
}
682
683
static void z_atan2(Rcomplex *r, Rcomplex *csn, Rcomplex *ccs)
684
0
{
685
0
    double complex dr, dcsn = toC99(csn), dccs = toC99(ccs);
686
0
    if (dccs == 0) {
687
0
  if(dcsn == 0) {
688
0
      r->r = NA_REAL; r->i = NA_REAL; /* Why not R_NaN? */
689
0
      return;
690
0
  } else {
691
0
      double y = creal(dcsn);
692
0
      if (ISNAN(y)) dr = y;
693
0
      else dr = ((y >= 0) ? M_PI_2 : -M_PI_2);
694
0
  }
695
0
    } else {
696
0
  dr = catan(dcsn / dccs);
697
0
  if(creal(dccs) < 0) dr += M_PI;
698
0
  if(creal(dr) > M_PI) dr -= 2 * M_PI;
699
0
    }
700
0
    SET_C99_COMPLEX(r, 0, dr);
701
0
}
702
703
704
  /* Complex Functions of Two Arguments */
705
706
typedef void (*cm2_fun)(Rcomplex *, Rcomplex *, Rcomplex *);
707
attribute_hidden SEXP complex_math2(SEXP call, SEXP op, SEXP args, SEXP env)
708
214
{
709
214
    cm2_fun f;
710
214
    switch (PRIMVAL(op)) {
711
0
    case 0: /* atan2 */
712
0
  f = z_atan2; break;
713
0
    case 10001: /* round */
714
0
  f = z_rround; break;
715
0
    case 10002: /* passed from do_log1arg */
716
0
    case 10010: /*   "     "    " */
717
214
    case 10003: /* passed from do_log */
718
214
  f = z_logbase; break;
719
0
    case 10004: /* signif */
720
0
  f = z_prec; break;
721
0
    default:
722
0
  error_return(_("unimplemented complex function"));
723
214
    }
724
725
214
    SEXP
726
214
  sa = PROTECT(coerceVector(CAR(args), CPLXSXP)),
727
214
  sb = PROTECT(coerceVector(CADR(args), CPLXSXP));
728
214
    R_xlen_t na = XLENGTH(sa), nb = XLENGTH(sb), n;
729
214
    if ((na == 0) || (nb == 0)) {
730
11
  UNPROTECT(2);
731
11
  return(allocVector(CPLXSXP, 0));
732
11
    }
733
203
    n = (na < nb) ? nb : na;
734
203
    SEXP sy = PROTECT(allocVector(CPLXSXP, n));
735
203
    const Rcomplex
736
203
  *a = COMPLEX_RO(sa),
737
203
  *b = COMPLEX_RO(sb);
738
203
    Rcomplex ai, bi, *y = COMPLEX(sy);
739
203
    R_xlen_t i, ia, ib;
740
203
    bool naflag = false;
741
203
    MOD_ITERATE2(n, na, nb, i, ia, ib, {
742
203
  ai = a[ia]; bi = b[ib];
743
203
  if(ISNA(ai.r) && ISNA(ai.i) &&
744
203
     ISNA(bi.r) && ISNA(bi.i)) {
745
203
      y[i].r = NA_REAL; y[i].i = NA_REAL;
746
203
  } else {
747
203
      f(&y[i], &ai, &bi);
748
203
      if ( (ISNAN(y[i].r) || ISNAN(y[i].i)) &&
749
203
     !(ISNAN(ai.r) || ISNAN(ai.i) || ISNAN(bi.r) || ISNAN(bi.i)) )
750
203
    naflag = true;
751
203
  }
752
203
    });
753
203
    if (naflag)
754
35
  warning("NaNs produced in function \"%s\"", PRIMNAME(op));
755
203
    if(n == na) {
756
162
  SHALLOW_DUPLICATE_ATTRIB(sy, sa);
757
162
    } else if(n == nb) {
758
41
  SHALLOW_DUPLICATE_ATTRIB(sy, sb);
759
41
    }
760
203
    UNPROTECT(3);
761
203
    return sy;
762
214
}
763
764
attribute_hidden SEXP do_complex(SEXP call, SEXP op, SEXP args, SEXP rho)
765
1.03k
{
766
    /* complex(length, real, imaginary) */
767
1.03k
    SEXP ans, re, im;
768
1.03k
    R_xlen_t i, na, nr, ni;
769
770
1.03k
    checkArity(op, args);
771
1.03k
    na = asInteger(CAR(args));
772
1.03k
    if(na == NA_INTEGER || na < 0)
773
0
  error(_("invalid length"));
774
1.03k
    PROTECT(re = coerceVector(CADR(args), REALSXP));
775
1.03k
    PROTECT(im = coerceVector(CADDR(args), REALSXP));
776
1.03k
    nr = XLENGTH(re);
777
1.03k
    ni = XLENGTH(im);
778
    /* is always true: if (na >= 0) {*/
779
1.03k
    na = (nr > na) ? nr : na;
780
1.03k
    na = (ni > na) ? ni : na;
781
    /* }*/
782
1.03k
    ans = allocVector(CPLXSXP, na);
783
1.03k
    Rcomplex *pans = COMPLEX(ans);
784
19.2k
    for(i=0 ; i<na ; i++) {
785
18.1k
  pans[i].r = 0;
786
18.1k
  pans[i].i = 0;
787
18.1k
    }
788
1.03k
    UNPROTECT(2);
789
1.03k
    if(na > 0 && nr > 0) {
790
570
  const double *p_re = REAL_RO(re);
791
18.7k
  for(i=0 ; i<na ; i++)
792
18.1k
      pans[i].r = p_re[i%nr];
793
570
    }
794
1.03k
    if(na > 0 && ni > 0) {
795
570
  const double *p_im = REAL_RO(im);
796
18.7k
  for(i=0 ; i<na ; i++)
797
18.1k
      pans[i].i = p_im[i%ni];
798
570
    }
799
1.03k
    return ans;
800
1.03k
}
801
802
static void R_cpolyroot(double *opr, double *opi, int *degree,
803
      double *zeror, double *zeroi, bool *fail);
804
805
attribute_hidden SEXP do_polyroot(SEXP call, SEXP op, SEXP args, SEXP rho)
806
0
{
807
0
    checkArity(op, args);
808
0
    SEXP z = CAR(args);
809
0
    switch(TYPEOF(z)) {
810
0
    case CPLXSXP:
811
0
  PROTECT(z);
812
0
  break;
813
0
    case REALSXP:
814
0
    case INTSXP:
815
0
    case LGLSXP:
816
0
  PROTECT(z = coerceVector(z, CPLXSXP));
817
0
  break;
818
0
    default:
819
0
  UNIMPLEMENTED_TYPE("polyroot", z);
820
0
    }
821
822
0
    int i, n;
823
0
#ifdef LONG_VECTOR_SUPPORT
824
0
    R_xlen_t nn = XLENGTH(z);
825
0
    if (nn > R_SHORT_LEN_MAX) error("long vectors are not supported");
826
0
    n = (int) nn;
827
#else
828
    n = LENGTH(z);
829
#endif
830
0
    const Rcomplex *pz = COMPLEX_RO(z);
831
0
    int degree = 0; // := max{i; z[i] != 0}
832
0
    for(i = 0; i < n; i++) {
833
0
  if(pz[i].r!= 0.0 || pz[i].i != 0.0) degree = i;
834
0
    }
835
0
    n = degree + 1; /* omit trailing zeroes */
836
0
    SEXP r;
837
0
    if(degree >= 1) {
838
0
  SEXP zr, zi, rr, ri;
839
0
  PROTECT(rr = allocVector(REALSXP, n));
840
0
  PROTECT(ri = allocVector(REALSXP, n));
841
0
  PROTECT(zr = allocVector(REALSXP, n));
842
0
  PROTECT(zi = allocVector(REALSXP, n));
843
844
0
  double *p_rr = REAL(rr);
845
0
  double *p_ri = REAL(ri);
846
0
  double *p_zr = REAL(zr);
847
0
  double *p_zi = REAL(zi);
848
849
0
  for(i = 0 ; i < n ; i++) {
850
0
      if(!R_FINITE(pz[i].r) || !R_FINITE(pz[i].i))
851
0
    error(_("invalid polynomial coefficient"));
852
0
      p_zr[degree-i] = pz[i].r;
853
0
      p_zi[degree-i] = pz[i].i;
854
0
  }
855
0
  bool fail;
856
0
  R_cpolyroot(p_zr, p_zi, &degree, p_rr, p_ri, &fail);
857
0
  if(fail) error(_("root finding code failed"));
858
0
  UNPROTECT(2);
859
0
  r = allocVector(CPLXSXP, degree);
860
0
  Rcomplex *pr = COMPLEX(r);
861
0
  for(i = 0 ; i < degree ; i++) {
862
0
      pr[i].r = p_rr[i];
863
0
      pr[i].i = p_ri[i];
864
0
  }
865
0
  UNPROTECT(3);
866
0
    }
867
0
    else {
868
0
  UNPROTECT(1);
869
0
  r = allocVector(CPLXSXP, 0);
870
0
    }
871
0
    return r;
872
0
}
873
874
/* Formerly src/appl/cpoly.c:
875
 *
876
 *  Copyright (C) 1997-1998 Ross Ihaka
877
 *  Copyright (C) 1999-2001 R Core Team
878
 *
879
 *  cpoly finds the zeros of a complex polynomial.
880
 *
881
 *  On Entry
882
 *
883
 *  opr, opi      -  double precision vectors of real and
884
 *       imaginary parts of the coefficients in
885
 *       order of decreasing powers.
886
 *
887
 *  degree        -  int degree of polynomial.
888
 *
889
 *
890
 *  On Return
891
 *
892
 *  zeror, zeroi  -  output double precision vectors of
893
 *       real and imaginary parts of the zeros.
894
 *
895
 *  fail        -  output int parameter,  true  only if
896
 *       leading coefficient is zero or if cpoly
897
 *       has found fewer than degree zeros.
898
 *
899
 *  The program has been written to reduce the chance of overflow
900
 *  occurring. If it does occur, there is still a possibility that
901
 *  the zerofinder will work provided the overflowed quantity is
902
 *  replaced by a large number.
903
 *
904
 *  This is a C translation of the following.
905
 *
906
 *  TOMS Algorithm 419
907
 *  Jenkins and Traub.
908
 *  Comm. ACM 15 (1972) 97-99.
909
 *
910
 *  Ross Ihaka
911
 *  February 1997
912
 */
913
914
#include <R_ext/Arith.h> /* for declaration of hypot */
915
#include <R_ext/Memory.h> /* for declaration of R_alloc */
916
917
#include <float.h> /* for FLT_RADIX */
918
919
#include <Rmath.h> /* for R_pow_di */
920
921
static void calct(bool *);
922
static bool fxshft(int, double *, double *);
923
static bool vrshft(int, double *, double *);
924
static void nexth(bool);
925
static void noshft(int);
926
927
static void polyev(int, double, double,
928
       double *, double *, double *, double *, double *, double *);
929
static double errev(int, double *, double *, double, double, double, double);
930
static double cpoly_cauchy(int, double *, double *);
931
static double cpoly_scale(int, double *, double, double, double, double);
932
static void cdivid(double, double, double, double, double *, double *);
933
934
/* Global Variables (too many!) */
935
936
static int nn;
937
static double *pr, *pi, *hr, *hi, *qpr, *qpi, *qhr, *qhi, *shr, *shi;
938
static double sr, si;
939
static double tr, ti;
940
static double pvr, pvi;
941
942
static const double eta =  DBL_EPSILON;
943
static const double are = /* eta = */DBL_EPSILON;
944
static const double mre = 2. * M_SQRT2 * /* eta, i.e. */DBL_EPSILON;
945
static const double infin = DBL_MAX;
946
947
static void R_cpolyroot(double *opr, double *opi, int *degree,
948
      double *zeror, double *zeroi, bool *fail)
949
0
{
950
0
    static const double smalno = DBL_MIN;
951
0
    static const double base = (double)FLT_RADIX;
952
0
    static int d_n, i, i1, i2;
953
0
    static double zi, zr, xx, yy;
954
0
    static double bnd, xxx;
955
0
    bool conv;
956
0
    int d1;
957
0
    double *tmp;
958
0
    static const double cosr =/* cos 94 */ -0.06975647374412529990;
959
0
    static const double sinr =/* sin 94 */  0.99756405025982424767;
960
0
    xx = M_SQRT1_2;/* 1/sqrt(2) = 0.707.... */
961
962
0
    yy = -xx;
963
0
    *fail = false;
964
965
0
    nn = *degree;
966
0
    d1 = nn - 1;
967
968
    /* algorithm fails if the leading coefficient is zero. */
969
970
0
    if (opr[0] == 0. && opi[0] == 0.) {
971
0
  *fail = true;
972
0
  return;
973
0
    }
974
975
    /* remove the zeros at the origin if any. */
976
977
0
    while (opr[nn] == 0. && opi[nn] == 0.) {
978
0
  d_n = d1-nn+1;
979
0
  zeror[d_n] = 0.;
980
0
  zeroi[d_n] = 0.;
981
0
  nn--;
982
0
    }
983
0
    nn++;
984
    /*-- Now, global var.  nn := #{coefficients} = (relevant degree)+1 */
985
986
0
    if (nn == 1) return;
987
988
    /* Use a single allocation as these as small */
989
0
    const void *vmax = vmaxget();
990
0
    tmp = (double *) R_alloc((size_t) (10*nn), sizeof(double));
991
0
    pr = tmp; pi = tmp + nn; hr = tmp + 2*nn; hi = tmp + 3*nn;
992
0
    qpr = tmp + 4*nn; qpi = tmp + 5*nn; qhr = tmp + 6*nn; qhi = tmp + 7*nn;
993
0
    shr = tmp + 8*nn; shi = tmp + 9*nn;
994
995
    /* make a copy of the coefficients and shr[] = | p[] | */
996
0
    for (i = 0; i < nn; i++) {
997
0
  pr[i] = opr[i];
998
0
  pi[i] = opi[i];
999
0
  shr[i] = hypot(pr[i], pi[i]);
1000
0
    }
1001
1002
    /* scale the polynomial with factor 'bnd'. */
1003
0
    bnd = cpoly_scale(nn, shr, eta, infin, smalno, base);
1004
0
    if (bnd != 1.) {
1005
0
  for (i=0; i < nn; i++) {
1006
0
      pr[i] *= bnd;
1007
0
      pi[i] *= bnd;
1008
0
  }
1009
0
    }
1010
1011
    /* start the algorithm for one zero */
1012
1013
0
    while (nn > 2) {
1014
1015
  /* calculate bnd, a lower bound on the modulus of the zeros. */
1016
1017
0
  for (i=0 ; i < nn ; i++)
1018
0
      shr[i] = hypot(pr[i], pi[i]);
1019
0
  bnd = cpoly_cauchy(nn, shr, shi);
1020
1021
  /* outer loop to control 2 major passes */
1022
  /* with different sequences of shifts */
1023
1024
0
  for (i1 = 1; i1 <= 2; i1++) {
1025
1026
      /* first stage calculation, no shift */
1027
1028
0
      noshft(5);
1029
1030
      /*  inner loop to select a shift */
1031
0
      for (i2 = 1; i2 <= 9; i2++) {
1032
1033
    /* shift is chosen with modulus bnd */
1034
    /* and amplitude rotated by 94 degrees */
1035
    /* from the previous shift */
1036
1037
0
    xxx= cosr * xx - sinr * yy;
1038
0
    yy = sinr * xx + cosr * yy;
1039
0
    xx = xxx;
1040
0
    sr = bnd * xx;
1041
0
    si = bnd * yy;
1042
1043
    /*  second stage calculation, fixed shift */
1044
1045
0
    conv = fxshft(i2 * 10, &zr, &zi);
1046
0
    if (conv)
1047
0
        goto L10;
1048
0
      }
1049
0
  }
1050
1051
  /* the zerofinder has failed on two major passes */
1052
  /* return empty handed */
1053
1054
0
  *fail = true;
1055
0
  vmaxset(vmax);
1056
0
  return;
1057
1058
  /* the second stage jumps directly to the third stage iteration.
1059
   * if successful, the zero is stored and the polynomial deflated.
1060
   */
1061
0
    L10:
1062
0
  d_n = d1+2 - nn;
1063
0
  zeror[d_n] = zr;
1064
0
  zeroi[d_n] = zi;
1065
0
  --nn;
1066
0
  for (i=0; i < nn ; i++) {
1067
0
      pr[i] = qpr[i];
1068
0
      pi[i] = qpi[i];
1069
0
  }
1070
0
    }/*while*/
1071
1072
    /*  calculate the final zero and return */
1073
0
    cdivid(-pr[1], -pi[1], pr[0], pi[0], &zeror[d1], &zeroi[d1]);
1074
1075
0
    vmaxset(vmax);
1076
0
    return;
1077
0
}
1078
1079
1080
/*  Computes the derivative polynomial as the initial
1081
 *  polynomial and computes l1 no-shift h polynomials.  */
1082
1083
static void noshft(int l1)
1084
0
{
1085
0
    int i, j, jj, n = nn - 1, nm1 = n - 1;
1086
1087
0
    double t1, t2, xni;
1088
1089
0
    for (i=0; i < n; i++) {
1090
0
  xni = (double)(nn - i - 1);
1091
0
  hr[i] = xni * pr[i] / n;
1092
0
  hi[i] = xni * pi[i] / n;
1093
0
    }
1094
1095
0
    for (jj = 1; jj <= l1; jj++) {
1096
1097
0
  if (hypot(hr[n-1], hi[n-1]) <=
1098
0
      eta * 10.0 * hypot(pr[n-1], pi[n-1])) {
1099
      /*  If the constant term is essentially zero, */
1100
      /*  shift h coefficients. */
1101
1102
0
      for (i = 1; i <= nm1; i++) {
1103
0
    j = nn - i;
1104
0
    hr[j-1] = hr[j-2];
1105
0
    hi[j-1] = hi[j-2];
1106
0
      }
1107
0
      hr[0] = 0.;
1108
0
      hi[0] = 0.;
1109
0
  }
1110
0
  else {
1111
0
      cdivid(-pr[nn-1], -pi[nn-1], hr[n-1], hi[n-1], &tr, &ti);
1112
0
      for (i = 1; i <= nm1; i++) {
1113
0
    j = nn - i;
1114
0
    t1 = hr[j-2];
1115
0
    t2 = hi[j-2];
1116
0
    hr[j-1] = tr * t1 - ti * t2 + pr[j-1];
1117
0
    hi[j-1] = tr * t2 + ti * t1 + pi[j-1];
1118
0
      }
1119
0
      hr[0] = pr[0];
1120
0
      hi[0] = pi[0];
1121
0
  }
1122
0
    }
1123
0
}
1124
1125
1126
/*  Computes l2 fixed-shift h polynomials and tests for convergence.
1127
 *  initiates a variable-shift iteration and returns with the
1128
 *  approximate zero if successful.
1129
 */
1130
static bool fxshft(int l2, double *zr, double *zi)
1131
0
{
1132
/*  l2    - limit of fixed shift steps
1133
 *  zr,zi - approximate zero if convergence (result TRUE)
1134
 *
1135
 * Return value indicates convergence of stage 3 iteration
1136
 *
1137
 * Uses global (sr,si), nn, pr[], pi[], .. (all args of polyev() !)
1138
*/
1139
1140
0
    bool pasd, h_s_0, test;
1141
0
    static double svsi, svsr;
1142
0
    static int i, j, n;
1143
0
    static double oti, otr;
1144
1145
0
    n = nn - 1;
1146
1147
    /* evaluate p at s. */
1148
1149
0
    polyev(nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi);
1150
1151
0
    test = true;
1152
0
    pasd = false;
1153
1154
    /* calculate first t = -p(s)/h(s). */
1155
1156
0
    calct(&h_s_0);
1157
1158
    /* main loop for one second stage step. */
1159
1160
0
    for (j=1; j<=l2; j++) {
1161
1162
0
  otr = tr;
1163
0
  oti = ti;
1164
1165
  /* compute next h polynomial and new t. */
1166
1167
0
  nexth(h_s_0);
1168
0
  calct(&h_s_0);
1169
0
  *zr = sr + tr;
1170
0
  *zi = si + ti;
1171
1172
  /* test for convergence unless stage 3 has */
1173
  /* failed once or this is the last h polynomial. */
1174
1175
0
  if (!h_s_0 && test && j != l2) {
1176
0
      if (hypot(tr - otr, ti - oti) >= hypot(*zr, *zi) * 0.5) {
1177
0
    pasd = false;
1178
0
      }
1179
0
      else if (! pasd) {
1180
0
    pasd = true;
1181
0
      }
1182
0
      else {
1183
1184
    /* the weak convergence test has been */
1185
    /* passed twice, start the third stage */
1186
    /* iteration, after saving the current */
1187
    /* h polynomial and shift. */
1188
1189
0
    for (i = 0; i < n; i++) {
1190
0
        shr[i] = hr[i];
1191
0
        shi[i] = hi[i];
1192
0
    }
1193
0
    svsr = sr;
1194
0
    svsi = si;
1195
0
    if (vrshft(10, zr, zi)) {
1196
0
        return true;
1197
0
    }
1198
1199
    /* the iteration failed to converge. */
1200
    /* turn off testing and restore */
1201
    /* h, s, pv and t. */
1202
1203
0
    test = false;
1204
0
    for (i=1 ; i<=n ; i++) {
1205
0
        hr[i-1] = shr[i-1];
1206
0
        hi[i-1] = shi[i-1];
1207
0
    }
1208
0
    sr = svsr;
1209
0
    si = svsi;
1210
0
    polyev(nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi);
1211
0
    calct(&h_s_0);
1212
0
      }
1213
0
  }
1214
0
    }
1215
1216
    /* attempt an iteration with final h polynomial */
1217
    /* from second stage. */
1218
1219
0
    return(vrshft(10, zr, zi));
1220
0
}
1221
1222
1223
/* carries out the third stage iteration.
1224
 */
1225
static bool vrshft(int l3, double *zr, double *zi)
1226
0
{
1227
/*  l3      - limit of steps in stage 3.
1228
 *  zr,zi   - on entry contains the initial iterate;
1229
 *        if the iteration converges it contains
1230
 *        the final iterate on exit.
1231
 * Returns TRUE if iteration converges
1232
 *
1233
 * Assign and uses  GLOBAL sr, si
1234
*/
1235
0
    bool h_s_0, b;
1236
0
    static int i, j;
1237
0
    static double r1, r2, mp, ms, tp, relstp;
1238
0
    static double omp;
1239
1240
0
    b = false;
1241
0
    sr = *zr;
1242
0
    si = *zi;
1243
1244
    /* main loop for stage three */
1245
1246
0
    for (i = 1; i <= l3; i++) {
1247
1248
  /* evaluate p at s and test for convergence. */
1249
0
  polyev(nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi);
1250
1251
0
  mp = hypot(pvr, pvi);
1252
0
  ms = hypot(sr, si);
1253
0
  if (mp <=  20. * errev(nn, qpr, qpi, ms, mp, /*are=*/eta, mre)) {
1254
0
      goto L_conv;
1255
0
  }
1256
1257
  /* polynomial value is smaller in value than */
1258
  /* a bound on the error in evaluating p, */
1259
  /* terminate the iteration. */
1260
1261
0
  if (i != 1) {
1262
1263
0
      if (!b && mp >= omp && relstp < .05) {
1264
1265
    /* iteration has stalled. probably a */
1266
    /* cluster of zeros. do 5 fixed shift */
1267
    /* steps into the cluster to force */
1268
    /* one zero to dominate. */
1269
1270
0
    tp = relstp;
1271
0
    b = true;
1272
0
    if (relstp < eta)
1273
0
        tp = eta;
1274
0
    r1 = sqrt(tp);
1275
0
    r2 = sr * (r1 + 1.) - si * r1;
1276
0
    si = sr * r1 + si * (r1 + 1.);
1277
0
    sr = r2;
1278
0
    polyev(nn, sr, si, pr, pi, qpr, qpi, &pvr, &pvi);
1279
0
    for (j = 1; j <= 5; ++j) {
1280
0
        calct(&h_s_0);
1281
0
        nexth(h_s_0);
1282
0
    }
1283
0
    omp = infin;
1284
0
    goto L10;
1285
0
      }
1286
0
      else {
1287
1288
    /* exit if polynomial value */
1289
    /* increases significantly. */
1290
1291
0
    if (mp * .1 > omp)
1292
0
        return false;
1293
0
      }
1294
0
  }
1295
0
  omp = mp;
1296
1297
  /* calculate next iterate. */
1298
1299
0
    L10:
1300
0
  calct(&h_s_0);
1301
0
  nexth(h_s_0);
1302
0
  calct(&h_s_0);
1303
0
  if (!h_s_0) {
1304
0
      relstp = hypot(tr, ti) / hypot(sr, si);
1305
0
      sr += tr;
1306
0
      si += ti;
1307
0
  }
1308
0
    }
1309
0
    return false;
1310
1311
0
L_conv:
1312
0
    *zr = sr;
1313
0
    *zi = si;
1314
0
    return true;
1315
0
}
1316
1317
static void calct(bool *h_s_0)
1318
0
{
1319
    /* computes  t = -p(s)/h(s).
1320
     * h_s_0   - logical, set true if h(s) is essentially zero. */
1321
1322
0
    int n = nn - 1;
1323
0
    double hvi, hvr;
1324
1325
    /* evaluate h(s). */
1326
0
    polyev(n, sr, si, hr, hi,
1327
0
     qhr, qhi, &hvr, &hvi);
1328
1329
0
    *h_s_0 = hypot(hvr, hvi) <= are * 10. * hypot(hr[n-1], hi[n-1]);
1330
0
    if (!*h_s_0) {
1331
0
  cdivid(-pvr, -pvi, hvr, hvi, &tr, &ti);
1332
0
    }
1333
0
    else {
1334
0
  tr = 0.;
1335
0
  ti = 0.;
1336
0
    }
1337
0
}
1338
1339
static void nexth(bool h_s_0)
1340
0
{
1341
    /* calculates the next shifted h polynomial.
1342
     * h_s_0 :  if TRUE  h(s) is essentially zero
1343
     */
1344
0
    int j, n = nn - 1;
1345
0
    double t1, t2;
1346
1347
0
    if (!h_s_0) {
1348
0
  for (j=1; j < n; j++) {
1349
0
      t1 = qhr[j - 1];
1350
0
      t2 = qhi[j - 1];
1351
0
      hr[j] = tr * t1 - ti * t2 + qpr[j];
1352
0
      hi[j] = tr * t2 + ti * t1 + qpi[j];
1353
0
  }
1354
0
  hr[0] = qpr[0];
1355
0
  hi[0] = qpi[0];
1356
0
    }
1357
0
    else {
1358
  /* if h(s) is zero replace h with qh. */
1359
1360
0
  for (j=1; j < n; j++) {
1361
0
      hr[j] = qhr[j-1];
1362
0
      hi[j] = qhi[j-1];
1363
0
  }
1364
0
  hr[0] = 0.;
1365
0
  hi[0] = 0.;
1366
0
    }
1367
0
}
1368

1369
/*--------------------- Independent Complex Polynomial Utilities ----------*/
1370
1371
static
1372
void polyev(int n,
1373
      double s_r, double s_i,
1374
      double *p_r, double *p_i,
1375
      double *q_r, double *q_i,
1376
      double *v_r, double *v_i)
1377
0
{
1378
    /* evaluates a polynomial  p  at  s  by the horner recurrence
1379
     * placing the partial sums in q and the computed value in v_.
1380
     */
1381
0
    int i;
1382
0
    double t;
1383
1384
0
    q_r[0] = p_r[0];
1385
0
    q_i[0] = p_i[0];
1386
0
    *v_r = q_r[0];
1387
0
    *v_i = q_i[0];
1388
0
    for (i = 1; i < n; i++) {
1389
0
  t = *v_r * s_r - *v_i * s_i + p_r[i];
1390
0
  q_i[i] = *v_i = *v_r * s_i + *v_i * s_r + p_i[i];
1391
0
  q_r[i] = *v_r = t;
1392
0
    }
1393
0
}
1394
1395
static
1396
double errev(int n, double *qr, double *qi,
1397
       double ms, double mp, double a_re, double m_re)
1398
0
{
1399
    /*  bounds the error in evaluating the polynomial by the horner
1400
     *  recurrence.
1401
     *
1402
     *  qr,qi  - the partial sum vectors
1403
     *  ms   - modulus of the point
1404
     *  mp   - modulus of polynomial value
1405
     * a_re,m_re - error bounds on complex addition and multiplication
1406
     */
1407
0
    double e;
1408
0
    int i;
1409
1410
0
    e = hypot(qr[0], qi[0]) * m_re / (a_re + m_re);
1411
0
    for (i=0; i < n; i++)
1412
0
  e = e*ms + hypot(qr[i], qi[i]);
1413
1414
0
    return e * (a_re + m_re) - mp * m_re;
1415
0
}
1416
1417
1418
static
1419
double cpoly_cauchy(int n, double *pot, double *q)
1420
0
{
1421
    /* Computes a lower bound on the moduli of the zeros of a polynomial
1422
     * pot[1:nn] is the modulus of the coefficients.
1423
     */
1424
0
    double f, x, delf, dx, xm;
1425
0
    int i, n1 = n - 1;
1426
1427
0
    pot[n1] = -pot[n1];
1428
1429
    /* compute upper estimate of bound. */
1430
1431
0
    x = exp((log(-pot[n1]) - log(pot[0])) / (double) n1);
1432
1433
    /* if newton step at the origin is better, use it. */
1434
1435
0
    if (pot[n1-1] != 0.) {
1436
0
  xm = -pot[n1] / pot[n1-1];
1437
0
  if (xm < x)
1438
0
      x = xm;
1439
0
    }
1440
1441
    /* chop the interval (0,x) unitl f le 0. */
1442
1443
0
    for(;;) {
1444
0
  xm = x * 0.1;
1445
0
  f = pot[0];
1446
0
  for (i = 1; i < n; i++)
1447
0
      f = f * xm + pot[i];
1448
0
  if (f <= 0.0) {
1449
0
      break;
1450
0
  }
1451
0
  x = xm;
1452
0
    }
1453
1454
0
    dx = x;
1455
1456
    /* do Newton iteration until x converges to two decimal places. */
1457
1458
0
    while (fabs(dx / x) > 0.005) {
1459
0
  q[0] = pot[0];
1460
0
  for(i = 1; i < n; i++)
1461
0
      q[i] = q[i-1] * x + pot[i];
1462
0
  f = q[n1];
1463
0
  delf = q[0];
1464
0
  for(i = 1; i < n1; i++)
1465
0
      delf = delf * x + q[i];
1466
0
  dx = f / delf;
1467
0
  x -= dx;
1468
0
    }
1469
0
    return x;
1470
0
}
1471
1472
static
1473
double cpoly_scale(int n, double *pot,
1474
       double eps, double BIG, double small, double base)
1475
0
{
1476
    /* Returns a scale factor to multiply the coefficients of the polynomial.
1477
     * The scaling is done to avoid overflow and to avoid
1478
     *  undetected underflow interfering with the convergence criterion.
1479
     * The factor is a power of the base.
1480
1481
     * pot[1:n] : modulus of coefficients of p
1482
     * eps,BIG,
1483
     * small,base - constants describing the floating point arithmetic.
1484
     */
1485
1486
0
    int i, ell;
1487
0
    double x, high, sc, lo, min_, max_;
1488
1489
    /* find largest and smallest moduli of coefficients. */
1490
0
    high = sqrt(BIG);
1491
0
    lo = small / eps;
1492
0
    max_ = 0.;
1493
0
    min_ = BIG;
1494
0
    for (i = 0; i < n; i++) {
1495
0
  x = pot[i];
1496
0
  if (x > max_) max_ = x;
1497
0
  if (x != 0. && x < min_)
1498
0
      min_ = x;
1499
0
    }
1500
1501
    /* scale only if there are very large or very small components. */
1502
1503
0
    if (min_ < lo || max_ > high) {
1504
0
  x = lo / min_;
1505
0
  if (x <= 1.)
1506
0
      sc = 1. / (sqrt(max_) * sqrt(min_));
1507
0
  else {
1508
0
      sc = x;
1509
0
      if (BIG / sc > max_)
1510
0
    sc = 1.0;
1511
0
  }
1512
0
  ell = (int) (log(sc) / log(base) + 0.5);
1513
0
  return R_pow_di(base, ell);
1514
0
    }
1515
0
    else return 1.0;
1516
0
}
1517
1518
1519
static
1520
void cdivid(double ar, double ai, double br, double bi,
1521
      double *cr, double *ci)
1522
0
{
1523
/* complex division c = a/b, i.e., (cr +i*ci) = (ar +i*ai) / (br +i*bi),
1524
   avoiding overflow. */
1525
1526
0
    double d, r;
1527
1528
0
    if (br == 0. && bi == 0.) {
1529
  /* division by zero, c = infinity. */
1530
0
  *cr = *ci = R_PosInf;
1531
0
    }
1532
0
    else if (fabs(br) >= fabs(bi)) {
1533
0
  r = bi / br;
1534
0
  d = br + r * bi;
1535
0
  *cr = (ar + ai * r) / d;
1536
0
  *ci = (ai - ar * r) / d;
1537
0
    }
1538
0
    else {
1539
0
  r = br / bi;
1540
0
  d = bi + r * br;
1541
0
  *cr = (ar * r + ai) / d;
1542
0
  *ci = (ai * r - ar) / d;
1543
0
    }
1544
0
}
1545
1546
/* static double cpoly_cmod(double *r, double *i)
1547
 * --> replaced by hypot() everywhere
1548
*/