Debian Codegraph @

dwsys/Polynomial.cpp

raw
1 /* Polynomial.cpp
2 *
3 * Copyright (C) 1993-2020 David Weenink
4 *
5 * This code is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
9 *
10 * This code is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this work. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /*
20 djmw 20020813 GPL header
21 djmw 20030619 Added SVD_compute before SVD_solve
22 djmw 20060510 Polynomial_to_Roots: changed behaviour. All roots found are now saved.
23 In previous version a nullptr pointer was returned. New error messages.
24 djmw 20071012 Added: oo_CAN_WRITE_AS_ENCODING.h
25 djmw 20071201 Melder_warning<n>
26 djmw 20080122 float -> double
27 djmw 20110304 Thing_new
28 */
29
30 #include "Roots.h"
31 #include "Polynomial.h"
32 #include "SVD.h"
33 #include "NUMmachar.h"
34
35 /* Evaluate polynomial and derivative jointly
36 c [1..n] -> degree n-1 !!
37 */
38 void Polynomial_evaluateWithDerivative (constPolynomial me, double x, double *out_f, double *out_df) {
39 longdouble p = my coefficients [my numberOfCoefficients], dp = 0.0;
40
41 for (integer i = my numberOfCoefficients - 1; i > 0; i --) {
42 dp = dp * x + p;
43 p = p * x + my coefficients [i];
44 }
45 if (out_f)
46 *out_f = (double) p;
47 if (out_df)
48 *out_df = (double) dp;
49 }
50
51 autoVEC Polynomial_evaluateDerivatives (constPolynomial me, double x, long numberOfDerivatives) {
52 /*
53 Evaluate polynomial c [1]+c [2]*x+...degree*x^degree in derivative [1] and the numberOfDerivatives
54 in derivatives in derivatives [2..numberOfDerivatives+1].
55 */
56 const integer degree = my numberOfCoefficients - 1;
57 autoVEC derivatives = zero_VEC (numberOfDerivatives + 1);
58 numberOfDerivatives = numberOfDerivatives > degree ? degree : numberOfDerivatives;
59
60 derivatives [1] = my coefficients [my numberOfCoefficients];
61
62 for (integer i = degree - 1; i >= 0; i--) {
63 const integer n = numberOfDerivatives < degree - i ? numberOfDerivatives : degree - i;
64 for (integer j = n; j >= 1; j --)
65 derivatives [j + 1] = derivatives [j + 1] * x + derivatives [j];
66 derivatives [1] = derivatives [1] * x + my coefficients [i + 1]; // evaluate polynomial (Horner)
67 }
68 double fact = 1.0;
69 for (integer j = 2; j <= numberOfDerivatives; j ++) {
70 fact *= j;
71 derivatives [j + 1] *= fact;
72 }
73 return derivatives;
74 }
75
76 /*
77 VECpolynomial_divide (constVEC u, constVEC v, VEC q, VEC r)
78
79 Purpose:
80 Find the quotient q(x) and the remainder r(x) polynomials that result from the division of
81 the polynomial u(x) = u [1] + u [2]*x^1 + u [3]*x^2 + ... + u [u.size]*x^(u.size-1) by the
82 polynomial v(x) = v [1] + v [2]*x^1 + v [3]*x^2 + ... + v [v.size]*x^(v.size-1), such that
83 u(x) = v(x)*q(x) + r(x).
84
85 The arrays u, v, q and r have to be dimensioned as u [1...u.size], v [1..v.size], q [1...u.size] and r [1...u.size],
86 respectively.
87 On return, the q [1..u.size-v.size] and r [1..v.size-1] contain the quotient and the remainder
88 polynomial coefficients, repectively.
89 See Knuth, The Art of Computer Programming, Volume 2: Seminumerical algorithms,
90 Third edition, Section 4.6.1 Algorithm D (the algorithm as described has been modified
91 to prevent overwriting of the u-polynomial).
92 */
93 static void VECpolynomial_divide (constVEC u, constVEC v, VEC q, VEC r) {
94 Melder_assert (q.size == u.size && r.size == u.size);
95 r <<= u;
96 q <<= 0.0;
97 for (integer k = u.size - v.size + 1; k > 0; k --) { /* D1 */
98 q [k] = r [v.size + k - 1] / v [v.size]; /* D2 with u -> r*/
99 for (integer j = v.size + k - 1; j >= k; j --)
100 r [j] -= q [k] * v [j - k + 1];
101 }
102 }
103
104
105 Thing_implement (Polynomial, FunctionSeries, 1);
106
107
108 /*
109 Symbolic evaluation of polynomial coefficients.
110 Recurrence: P [n] = (a [n] * x + b [n]) P [n-1] + c [n] P [n-2],
111 where P [n] is any orthogonal polynomial of degree n.
112 P [n] is an array of coefficients p [k] representing: p [1] + p [2] x + ... p [n+1] x^n.
113 Preconditions:
114 degree > 1;
115 pnm1 : polynomial of degree n - 1
116 pnm2 : polynomial of degree n - 2
117 */
118 double structPolynomial :: v_evaluate (double x) {
119 longdouble p = coefficients [numberOfCoefficients];
120 for (integer i = numberOfCoefficients - 1; i > 0; i --)
121 p = p * x + coefficients [i];
122 return (double) p;
123 }
124
125 dcomplex structPolynomial :: v_evaluate_z (dcomplex z) {
126 longdouble x = z.real(), y = z.imag();
127
128 longdouble pr = coefficients [numberOfCoefficients];
129 longdouble pi = 0.0;
130 for (integer i = numberOfCoefficients - 1; i > 0; i --) {
131 longdouble prtmp = pr;
132 pr = pr * x - pi * y + coefficients [i];
133 pi = prtmp * y + pi * x;
134 }
135 return { (double) pr, (double) pi };
136 }
137
138 void structPolynomial :: v_evaluateTerms (double x, VEC terms) {
139 Melder_assert (terms.size == numberOfCoefficients);
140 terms [1] = 1.0;
141 for (integer i = 2; i <= numberOfCoefficients; i ++)
142 terms [i] = terms [i - 1] * x;
143 }
144
145 void structPolynomial :: v_getExtrema (double x1, double x2, double *out_xmin, double *out_ymin, double *out_xmax, double *out_ymax) {
146 try {
147 const integer degree = numberOfCoefficients - 1;
148
149 double xmn = x1, ymn = v_evaluate (x1);
150 double xmx = x2, ymx = v_evaluate (x2);
151 if (ymn > ymx) {
152 std::swap (ymn, ymx);
153 std::swap (xmn, xmx);
154 }
155
156 if (degree < 2)
157 return;
158 autoPolynomial d = Polynomial_getDerivative (this);
159 autoRoots r = Polynomial_to_Roots (d.get());
160
161 for (integer i = 1; i <= degree - 1; i ++) {
162 const double x = r -> roots [i].real();
163 if (x > x1 && x < x2) {
164 const double y = v_evaluate (x);
165 if (y > ymx) {
166 ymx = y;
167 xmx = x;
168 } else if (y < ymn) {
169 ymn = y;
170 xmn = x;
171 }
172 }
173 }
174 if (out_xmin)
175 *out_xmin = xmn;
176 if (out_xmax)
177 *out_xmax = xmx;
178 if (out_ymin)
179 *out_ymin = ymn;
180 if (out_ymax)
181 *out_ymax = ymx;
182 } catch (MelderError) {
183 Melder_clearError ();
184 structFunctionSeries :: v_getExtrema (x1, x2, out_xmin, out_ymin, out_xmax, out_ymax);
185 }
186 }
187
188 autoPolynomial Polynomial_create (double xmin, double xmax, integer degree) {
189 try {
190 autoPolynomial me = Thing_new (Polynomial);
191 FunctionSeries_init (me.get(), xmin, xmax, degree + 1);
192 return me;
193 } catch (MelderError) {
194 Melder_throw (U"Polynomial not created.");
195 }
196 }
197
198 autoPolynomial Polynomial_createWithCoefficients (double lxmin, double lxmax, constVECVU const& coefficients) {
199 try {
200 autoPolynomial me = Thing_new (Polynomial);
201 FunctionSeries_initWithCoefficients (me.get(), lxmin, lxmax, coefficients, false);
202 return me;
203 } catch (MelderError) {
204 Melder_throw (U"Polynomial not created from string.");
205 }
206 }
207
208 void Polynomial_scaleCoefficients_monic (Polynomial me) {
209 const double cn = my coefficients [my numberOfCoefficients];
210 if (cn == 1 || my numberOfCoefficients <= 1)
211 return;
212 my coefficients.get() /= cn;
213 my coefficients [my numberOfCoefficients] = 1.0;
214 }
215
216 /*
217 Transform the polynomial as if the domain were [xmin, xmax].
218 Some polynomials (Legendre) are defined on the domain [-1,1]. The domain
219 for x may be extended to [xmin, xmax] by a transformation such as
220 x' = (2 * x - (xmin + xmax)) / (xmax - xmin) -1 < x' < x.
221 This procedure transforms x' back to x.
222 */
223 autoPolynomial Polynomial_scaleX (Polynomial me, double xmin, double xmax) {
224 try {
225 Melder_assert (xmin < xmax);
226
227 autoPolynomial thee = Polynomial_create (xmin, xmax, my numberOfCoefficients - 1);
228 thy coefficients [1] = my coefficients [1];
229 if (my numberOfCoefficients == 1)
230 return thee;
231 /*
232 x = a x + b
233 Constraints:
234 my xmin = a xmin + b; a = (my xmin - my xmax) / (xmin - xmax);
235 my xmax = a xmax + b; b = my xmin - a * xmin
236 */
237 const double a = (my xmin - my xmax) / (xmin - xmax);
238 const double b = my xmin - a * xmin;
239 thy coefficients [2] = my coefficients [2] * a;
240 thy coefficients [1] += my coefficients [2] * b;
241 if (my numberOfCoefficients == 2)
242 return thee;
243 autoVEC pn = zero_VEC (my numberOfCoefficients);
244 autoVEC pnm1 = zero_VEC (my numberOfCoefficients);
245 autoVEC pnm2 = zero_VEC (my numberOfCoefficients);
246
247 // Start the recursion: P [2] = a x + b; P [1] = 1;
248
249 pnm1 [2] = a;
250 pnm1 [1] = b;
251 pnm2 [1] = 1.0;
252 for (integer n = 2; n <= my numberOfCoefficients - 1; n ++) {
253 NUMpolynomial_recurrence (pn.part (1, n + 1), a, b, 0.0, pnm1.get(), pnm2.get());
254 if (my coefficients [n + 1] != 0.0)
255 for (integer j = 1; j <= n + 1; j ++)
256 thy coefficients [j] += my coefficients [n + 1] * pn [j];
257 autoVEC pn_old = std::move (pn);
258 pn = std::move (pnm2);
259 pnm2 = std::move (pnm1);
260 pnm1 = std::move (pn_old);
261 }
262 return thee;
263 } catch (MelderError) {
264 Melder_throw (me, U": cannot scale.");
265 }
266 }
267
268 double Polynomial_evaluate (Polynomial me, double x) {
269 return my v_evaluate (x);
270 }
271
272 dcomplex Polynomial_evaluate_z (Polynomial me, dcomplex z) {
273 return my v_evaluate_z (z);
274 }
275
276 autoPolynomial Polynomial_getDerivative (Polynomial me) {
277 try {
278 if (my numberOfCoefficients == 1)
279 return Polynomial_create (my xmin, my xmax, 0);
280 autoPolynomial thee = Polynomial_create (my xmin, my xmax, my numberOfCoefficients - 2);
281 for (integer i = 1; i <= thy numberOfCoefficients; i ++)
282 thy coefficients [i] = i * my coefficients [i + 1];
283 return thee;
284 } catch (MelderError) {
285 Melder_throw (me, U": no derivative created.");
286 }
287 }
288
289 autoPolynomial Polynomial_getPrimitive (Polynomial me, double constant) {
290 try {
291 autoPolynomial thee = Polynomial_create (my xmin, my xmax, my numberOfCoefficients);
292 for (integer i = 1; i <= my numberOfCoefficients; i ++)
293 thy coefficients [i + 1] = my coefficients [i] / i;
294 thy coefficients [1] = constant;
295 return thee;
296 } catch (MelderError) {
297 Melder_throw (me, U": no primitive created.");
298 }
299 }
300
301 /* P(x)= (x-roots [1])*(x-roots [2])*..*(x-roots [numberOfRoots]) */
302 void Polynomial_initFromRealRoots (Polynomial me, constVECVU const& roots) {
303 try {
304 my resize (roots.size + 1);
305 integer n = 1;
306 my coefficients [1] = - roots [1];
307 my coefficients [2] = 1.0;
308 for (integer iroot = 2; iroot <= roots.size; iroot ++) {
309 my coefficients [n + 2] = my coefficients [n + 1];
310 for (integer j = n; j >= 1; j --)
311 my coefficients [j + 1] = my coefficients [j] - my coefficients [j + 1] * roots [iroot];
312 my coefficients [1] *= -roots [iroot];
313 n ++;
314 }
315 } catch (MelderError) {
316 Melder_throw (me, U": not initalized from real roots.");
317 }
318 }
319
320 autoPolynomial Polynomial_createFromRealRoots (double xmin, double xmax, constVECVU const& roots) {
321 try {
322 autoPolynomial me = Thing_new (Polynomial);
323 FunctionSeries_init (me.get(), xmin, xmax, roots.size + 1);
324 Polynomial_initFromRealRoots (me.get(), roots);
325 return me;
326 } catch (MelderError) {
327 Melder_throw (U"Polynomial not created from roots.");
328 }
329
330 }
331
332 /* Product (i=1; a.size; (1 + a [i] * x + x^2)
333 * Postcondition : my numberOfCoeffcients = 2 * a.size + 1
334 */
335 void Polynomial_initFromProductOfSecondOrderTerms (Polynomial me, constVECVU const& a) {
336 my resize (2 * a.size + 1);
337 my coefficients [1] = my coefficients [3] = 1.0;
338 my coefficients [2] = a [1];
339 integer ncoef = 3;
340 for (integer i = 2; i <= a.size; i ++) {
341 my coefficients [ncoef + 1] = a [i] * my coefficients [ncoef] + my coefficients [ncoef - 1];
342 my coefficients [ncoef + 2] = my coefficients [ncoef];
343 for (integer j = ncoef; j > 2; j --)
344 my coefficients [j] += a [i] * my coefficients [j - 1] + my coefficients [j - 2];
345 my coefficients [2] += a [i]; // a [i] * my coefficients [1]
346 ncoef += 2;
347 }
348 Melder_assert (my numberOfCoefficients == ncoef);
349 }
350
351 autoPolynomial Polynomial_createFromProductOfSecondOrderTerms (double xmin, double xmax, constVECVU const& a) {
352 try {
353 autoPolynomial me = Thing_new (Polynomial);
354 FunctionSeries_init (me.get(), xmin, xmax, 2 * a.size + 1);
355 Polynomial_initFromProductOfSecondOrderTerms (me.get(), a);
356 return me;
357 } catch (MelderError) {
358 Melder_throw (U"Polynomial not created from second order terms string.");
359 }
360 }
361
362 double Polynomial_getArea (Polynomial me, double xmin, double xmax) {
363 if (xmax >= xmin) {
364 xmin = my xmin;
365 xmax = my xmax;
366 }
367 autoPolynomial p = Polynomial_getPrimitive (me, 0);
368 double area = FunctionSeries_evaluate (p.get(), xmax) - FunctionSeries_evaluate (p.get(), xmin);
369 return area;
370 }
371
372 /* P(x) * (x-a)
373 * Postcondition: my numberOfCoefficients = old_numberOfCoefficients + 1
374 */
375 void Polynomial_multiply_firstOrderFactor (Polynomial me, double factor) {
376 const integer n = my numberOfCoefficients;
377 my resize (n + 1);
378
379 my coefficients [n + 1] = my coefficients [n];
380 for (integer j = n; j >= 2; j --)
381 my coefficients [j] = my coefficients [j - 1] - my coefficients [j] * factor;
382 my coefficients [1] *= -factor;
383 }
384
385 /*
386 P(x) * (x^2 - a)
387 Postcondition: my numberOfCoefficients = old_numberOfCoefficients + 2
388 */
389 void Polynomial_multiply_secondOrderFactor (Polynomial me, double factor) {
390 const integer n = my numberOfCoefficients;
391 my resize (n + 2);
392 my coefficients [n + 2] = my coefficients [n];
393 my coefficients [n + 1] = my coefficients [n - 1];
394 for (integer j = n; j >= 3; j --)
395 my coefficients [j] = my coefficients [j - 2] - factor * my coefficients [j];
396 my coefficients [2] *= - factor;
397 my coefficients [1] *= - factor;
398 }
399
400 autoPolynomial Polynomials_multiply (Polynomial me, Polynomial thee) {
401 try {
402 const integer n1 = my numberOfCoefficients, n2 = thy numberOfCoefficients;
403 Melder_require (my xmax > thy xmin && my xmin < thy xmax,
404 U"Domains should overlap.");
405 const double xmin = my xmin > thy xmin ? my xmin : thy xmin;
406 const double xmax = my xmax < thy xmax ? my xmax : thy xmax;
407 autoPolynomial him = Polynomial_create (xmin, xmax, n1 + n2 - 2);
408 for (integer i = 1; i <= n1; i ++)
409 for (integer j = 1; j <= n2; j ++)
410 his coefficients [i + j - 1] += my coefficients [i] * thy coefficients [j];
411 return him;
412 } catch (MelderError) {
413 Melder_throw (U"Polynomials not multiplied.");
414 }
415 }
416
417 void Polynomials_divide (Polynomial me, Polynomial thee, autoPolynomial *out_q, autoPolynomial *out_r) {
418 if (! out_q && ! out_r)
419 return;
420 autoVEC qc = zero_VEC (my numberOfCoefficients);
421 autoVEC rc = zero_VEC (my numberOfCoefficients);
422 autoPolynomial aq, ar;
423 VECpolynomial_divide (my coefficients.get (), thy coefficients.get (), qc.get (), rc.get ());
424 if (out_q) {
425 const integer degree = std::max (my numberOfCoefficients - thy numberOfCoefficients, 0_integer);
426 aq = Polynomial_create (my xmin, my xmax, degree);
427 if (degree >= 0)
428 aq -> coefficients.get () <<= qc.part (1, degree + 1);
429 *out_q = aq.move();
430 }
431 if (out_r) {
432 integer degree = thy numberOfCoefficients - 2;
433 if (my numberOfCoefficients >= thy numberOfCoefficients)
434 degree --;
435 if (degree < 0)
436 degree = 0;
437 while (degree > 1 && rc [degree] == 0.0)
438 degree --;
439 ar = Polynomial_create (my xmin, my xmax, degree);
440 ar -> coefficients.all() <<= rc.part (1, degree + 1);
441 *out_r = ar.move();
442 }
443 }
444
445 static double dpoly_nr (double x, double *df, void *closure) {
446 double f;
447 Polynomial_evaluateWithDerivative ((Polynomial) closure, x, & f, df);
448 return f;
449 }
450
451 double Polynomial_findOneSimpleRealRoot_nr (Polynomial me, double xmin, double xmax) {
452 double root = NUMnrbis (dpoly_nr, xmin, xmax, me);
453 return root;
454 }
455
456 static double dpoly_r (double x, void *closure) {
457 return Polynomial_evaluate ((Polynomial) closure, x);
458 }
459
460 double Polynomial_findOneSimpleRealRoot_ridders (Polynomial me, double xmin, double xmax) {
461 return NUMridders (dpoly_r, xmin, xmax, me);
462 }
463
464 void Polynomial_divide_firstOrderFactor (Polynomial me, double factor, double *out_remainder) { // P(x)/(x-a)
465 double remainder = undefined;
466 if (my numberOfCoefficients > 1) {
467 remainder = my coefficients [my numberOfCoefficients];
468 for (integer j = my numberOfCoefficients - 1; j > 0; j --) {
469 const double tmp = my coefficients [j];
470 my coefficients [j] = remainder;
471 remainder = tmp + remainder * factor;
472 }
473 my numberOfCoefficients --;
474 } else {
475 my coefficients [1] = 0.0;
476 }
477 if (out_remainder)
478 *out_remainder = remainder;
479 }
480
481 void Polynomial_divide_secondOrderFactor (Polynomial me, double factor) {
482 if (my numberOfCoefficients > 2) {
483 integer n = my numberOfCoefficients;
484 /*
485 c [1]+c [2]*x...c [n+1]*x^n / (x^2 - a) = r [1]+r [2]*x+...r [n-1]x^(n-2) + possible remainder a [1]+a [2]*x)
486 r [j] = c [j+2]+factor*r [j+2]
487 */
488 double cjp2 = my coefficients [n];
489 double cjp1 = my coefficients [n - 1];
490 my coefficients [n] = my coefficients [n - 1] = 0.0;
491 for (integer j = n - 2; j > 0; j --) {
492 const double cj = my coefficients [j];
493 my coefficients [j] = cjp2 + factor * my coefficients [j + 2];
494 cjp2 = cjp1;
495 cjp1 = cj;
496 }
497 my numberOfCoefficients -= 2;
498 } else {
499 my numberOfCoefficients = 1;
500 my coefficients [1] = 0.0;
501 }
502 }
503
504 void Roots_setRoot (mutableRoots me, integer index, double re, double im) {
505 Melder_require (index >= 1 && index <= my numberOfRoots,
506 U"Index should be in interval [1, ", my numberOfRoots, U"].");
507 my roots [index]. real (re);
508 my roots [index]. imag (im);
509 }
510
511 dcomplex Roots_evaluate_z (constRoots me, dcomplex z) {
512 dcomplex result = {1, 0};
513 for (integer i = 1; i <= my numberOfRoots; i ++) {
514 dcomplex t = dcomplex_sub (z, my roots [i]);
515 result = dcomplex_mul (result, t);
516 }
517 return result;
518 }
519
520 /* end of file Polynomial.cpp */