Debian Codegraph @

src/numerical/polynom.rs

raw symbols SCIP
1 // Copyright (c) 2017, Mikhail Vorotilov
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are met:
6 //
7 // * Redistributions of source code must retain the above copyright notice, this
8 // list of conditions and the following disclaimer.
9 //
10 // * Redistributions in binary form must reproduce the above copyright notice,
11 // this list of conditions and the following disclaimer in the documentation
12 // and/or other materials provided with the distribution.
13 //
14 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18 // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24
25 use super::super::find_roots_cubic;
26 use super::super::find_roots_linear;
27 use super::super::find_roots_quadratic;
28 use super::super::FloatType;
29 use super::Convergency;
30 use super::Interval;
31 use super::Sample;
32 use super::SearchError;
33
34 #[derive(Debug, PartialEq)]
35 struct ValueAndDerivative<F>
36 where
37 F: FloatType,
38 {
39 value: Sample<F>,
40 derivative: F,
41 }
42
43 trait Polynom<F>
44 where
45 F: FloatType,
46 {
47 fn value(&self, x: &F) -> F;
48 fn value_and_derivative(&self, x: &F) -> ValueAndDerivative<F>;
49 fn find_root(&self, bracketed_start: &mut Interval<F>, convergency: &mut dyn Convergency<F>) -> Result<F, SearchError>;
50 fn derivative_polynom(&self) -> Vec<F>;
51 fn to_string(&self) -> String;
52 }
53
54 impl<F> Polynom<F> for [F]
55 where
56 F: FloatType,
57 {
58 fn value(&self, x: &F) -> F {
59 let mut result = F::zero();
60 let mut xn = F::one();
61
62 // Sum starting with a0
63 for a in self.iter().rev() {
64 result = result + *a * xn;
65 xn = xn * *x;
66 }
67
68 // The highest coefficient of the normalized polynom is 1
69 result + xn
70 }
71
72 fn value_and_derivative(&self, x: &F) -> ValueAndDerivative<F> {
73 let mut xn = F::one(); // x^n for SUM(A(n)*x^(n))
74 let mut value = F::zero();
75
76 let mut xn1 = F::zero(); // x^n-1 for SUM(n*A(n-1)*x^(n-1))
77 let mut derivative = F::zero();
78 let mut n = F::zero();
79
80 // Sum starting with a0
81 for a in self.iter().rev() {
82 value = value + *a * xn;
83 derivative = derivative + *a * n * xn1;
84 xn1 = xn;
85 xn = xn * *x;
86 n = n + F::one();
87 }
88
89 // The highest coefficient of the normalized polynom is 1
90 ValueAndDerivative {
91 value: Sample { x: *x, y: value + xn },
92 derivative: derivative + n * xn1,
93 }
94 }
95
96 fn find_root(&self, bracketed_start: &mut Interval<F>, convergency: &mut dyn Convergency<F>) -> Result<F, SearchError> {
97 if bracketed_start.is_bracketed() {
98 let interval = bracketed_start;
99 let mut iter = 0;
100 loop {
101 if convergency.is_root_found(interval.begin.y) {
102 break Ok(interval.begin.x);
103 } else if convergency.is_root_found(interval.end.y) {
104 break Ok(interval.end.x);
105 } else if interval.is_converged(convergency) {
106 break Ok(interval.middle());
107 } else {
108 let middle = self.value_and_derivative(&interval.middle());
109 let next_sample = if middle.derivative != F::zero() {
110 let newton_raphson = middle.value.x - middle.value.y / middle.derivative;
111 if newton_raphson >= interval.begin.x && newton_raphson <= interval.end.x {
112 let newton_raphson_value = self.value(&newton_raphson);
113 if newton_raphson_value.abs() < middle.value.y.abs() {
114 Sample {
115 x: newton_raphson,
116 y: newton_raphson_value,
117 }
118 } else {
119 middle.value
120 }
121 } else {
122 middle.value
123 }
124 } else {
125 middle.value
126 };
127 if interval.begin.is_bracketed_with(&next_sample) {
128 interval.end = Sample {
129 x: next_sample.x,
130 y: next_sample.y,
131 };
132 } else {
133 interval.begin = Sample {
134 x: next_sample.x,
135 y: next_sample.y,
136 };
137 }
138 }
139 iter = iter + 1;
140 if convergency.is_iteration_limit_reached(iter) {
141 break Err(SearchError::NoConvergency);
142 }
143 }
144 } else {
145 Err(SearchError::NoBracketing)
146 }
147 }
148
149 fn derivative_polynom(&self) -> Vec<F> {
150 let mut result = Vec::from(self);
151 result.truncate(self.len() - 1);
152 let n: F = F::from(self.len() as i16);
153 let mut ni = F::one();
154
155 for x in result.iter_mut().rev() {
156 *x = (*x * ni) / n;
157 ni = ni + F::one();
158 }
159
160 result
161 }
162
163 fn to_string(&self) -> String {
164 let mut result = String::new();
165 let mut p = self.len();
166
167 if self.len() == 0 {
168 result.push_str("x=0")
169 } else {
170 result.push_str(&format!("x^{:?}", p));
171 for x in self.iter() {
172 p = p - 1;
173 if *x != F::zero() {
174 if *x > F::zero() {
175 result.push_str(&format!("+{:?}*x^{:?}", *x, p));
176 } else {
177 result.push_str(&format!("-{:?}*x^{:?}", -*x, p));
178 }
179 }
180 }
181 }
182 result
183 }
184 }
185
186 /// Interval for searching roots
187 enum SearchInterval<F>
188 where
189 F: FloatType,
190 {
191 /// [-infinity .. +infinity]
192 Whole,
193 /// [-infinity .. x]
194 First(Sample<F>),
195 /// [x .. +infinity ]
196 Last(Sample<F>),
197 /// [x1 .. x2 ]
198 Middle(Interval<F>),
199 }
200
201 enum BracketingDirection {
202 TowardsPositive,
203 TowardsNegative,
204 }
205
206 fn initial_bracket<F>(
207 initial_sample: &Sample<F>,
208 direction: &BracketingDirection,
209 polynom: &[F],
210 derivative_polynom: &[F],
211 convergency: &mut dyn Convergency<F>,
212 ) -> Result<Interval<F>, SearchError>
213 where
214 F: FloatType,
215 {
216 let mut iter = 0;
217 let towards_positive = match direction {
218 &BracketingDirection::TowardsPositive => true,
219 &BracketingDirection::TowardsNegative => false,
220 };
221 let mut step = if towards_positive { F::one() } else { -F::one() };
222 let initial_copy = Sample {
223 x: initial_sample.x,
224 y: initial_sample.y,
225 };
226 let mut next_x = initial_sample.x + step;
227 let result = loop {
228 let mut next_y = polynom.value(&next_x);
229 let mut next_sample = Sample { x: next_x, y: next_y };
230 if next_sample.is_bracketed_with(&initial_sample) {
231 break Ok(if towards_positive {
232 Interval {
233 begin: initial_copy,
234 end: next_sample,
235 }
236 } else {
237 Interval {
238 begin: next_sample,
239 end: initial_copy,
240 }
241 });
242 } else {
243 let derivative = derivative_polynom.value(&next_x);
244 if derivative > F::zero() {
245 next_x = next_x - next_y / derivative;
246 next_y = polynom.value(&next_x);
247 next_sample = Sample { x: next_x, y: next_y };
248 if next_sample.is_bracketed_with(&initial_sample) {
249 break Ok(if towards_positive {
250 Interval {
251 begin: initial_copy,
252 end: next_sample,
253 }
254 } else {
255 Interval {
256 begin: next_sample,
257 end: initial_copy,
258 }
259 });
260 }
261 };
262 step = step * F::from(2i16);
263 next_x = next_x + step;
264 iter = iter + 1;
265 if convergency.is_iteration_limit_reached(iter) {
266 break Err(SearchError::NoConvergency);
267 };
268 }
269 };
270 result
271 }
272
273 fn narrow_down<F>(
274 initial_interval: &SearchInterval<F>,
275 polynom: &[F],
276 derivative_polynom: &[F],
277 convergency: &mut dyn Convergency<F>,
278 ) -> Result<Interval<F>, SearchError>
279 where
280 F: FloatType,
281 {
282 match initial_interval {
283 &SearchInterval::Whole => {
284 let zero_sample = Sample {
285 x: F::zero(),
286 y: polynom.value(&F::zero()),
287 };
288 let zero_interval = if zero_sample.y > F::zero() {
289 SearchInterval::First(zero_sample)
290 } else {
291 SearchInterval::Last(zero_sample)
292 };
293 narrow_down(&zero_interval, polynom, derivative_polynom, convergency)
294 }
295 &SearchInterval::First(ref end) => initial_bracket(
296 &end,
297 &BracketingDirection::TowardsNegative,
298 polynom,
299 derivative_polynom,
300 convergency,
301 ),
302 &SearchInterval::Last(ref begin) => initial_bracket(
303 &begin,
304 &BracketingDirection::TowardsPositive,
305 polynom,
306 derivative_polynom,
307 convergency,
308 ),
309 &SearchInterval::Middle(ref interval) => {
310 if interval.is_bracketed() {
311 let middle_x = if interval.begin.y == interval.end.y {
312 (interval.begin.x + interval.end.x) / F::from(2i16)
313 } else {
314 interval.begin.x - interval.begin.y * (interval.end.x - interval.begin.x) / (interval.end.y - interval.begin.y)
315 };
316 let mut middle_sample = Sample {
317 x: middle_x,
318 y: polynom.value(&middle_x),
319 };
320 let derivative = derivative_polynom.value(&middle_x);
321 if derivative != F::zero() {
322 let closer_x = middle_sample.x - middle_sample.y / derivative;
323 if closer_x >= interval.begin.x && closer_x <= interval.end.x {
324 middle_sample = Sample {
325 x: closer_x,
326 y: polynom.value(&closer_x),
327 };
328 }
329 }
330 if interval.begin.is_bracketed_with(&middle_sample) {
331 Ok(Interval {
332 begin: Sample {
333 x: interval.begin.x,
334 y: interval.begin.y,
335 },
336 end: middle_sample,
337 })
338 } else {
339 Ok(Interval {
340 begin: middle_sample,
341 end: Sample {
342 x: interval.end.x,
343 y: interval.end.y,
344 },
345 })
346 }
347 } else {
348 Err(SearchError::NoBracketing)
349 }
350 }
351 }
352 }
353
354 fn find_root_intervals<F>(
355 polynom: &[F],
356 derivative_polynom: &[F],
357 convergency: &mut dyn Convergency<F>,
358 ) -> Result<Vec<SearchInterval<F>>, SearchError>
359 where
360 F: FloatType,
361 {
362 let mut result = Vec::new();
363 let derivative_roots = find_roots_sturm(&derivative_polynom, convergency);
364 let symmetric_polynom = polynom.len() % 2 == 0;
365 let mut expect_positive = !symmetric_polynom;
366 let mut previous_interval: SearchInterval<F> = SearchInterval::Whole;
367 // Iterate through all roots of the derivative polynom
368 for derivative_root in derivative_roots.iter().filter_map(|s| match s {
369 &Ok(ref x) => Some(x),
370 &Err(_) => None,
371 }) {
372 let value = polynom.value(derivative_root);
373 if (expect_positive && value >= F::zero()) || (!expect_positive && value < F::zero()) {
374 // Transition found
375 let interval_to_add = match &previous_interval {
376 &SearchInterval::Whole => SearchInterval::First(Sample {
377 x: *derivative_root,
378 y: value,
379 }),
380 &SearchInterval::First(ref previous_end) => SearchInterval::Middle(Interval {
381 begin: Sample {
382 x: previous_end.x,
383 y: previous_end.y,
384 },
385 end: Sample {
386 x: *derivative_root,
387 y: value,
388 },
389 }),
390 _ => panic!("Unexpected type of the previous root interval!"),
391 };
392 result.push(interval_to_add);
393 expect_positive = !expect_positive;
394 }
395 previous_interval = SearchInterval::First(Sample {
396 x: *derivative_root,
397 y: value,
398 });
399 }
400 // All roots are checked, now the final step
401 match previous_interval {
402 SearchInterval::Whole => {
403 if !symmetric_polynom {
404 result.push(SearchInterval::Whole);
405 }
406 Ok(result)
407 }
408 SearchInterval::First(sample) => {
409 if sample.x < F::zero() {
410 result.push(SearchInterval::Last(sample));
411 }
412 Ok(result)
413 }
414 _ => Err(SearchError::NoBracketing),
415 }
416 }
417
418 /// Find all roots of the normalized polynomial
419 /// x^n + a[0]*x^(n-1) + a[1]*x^(n-2) + ... + a[n-1] = 0
420 /// using the Sturm's theorem recursively.
421 ///
422 /// # Examples
423 ///
424 /// ```
425 /// use roots::find_roots_sturm;
426 ///
427 /// let polynom = &[1f64,1f64,1f64,1f64,1f64,1f64];
428 ///
429 /// let roots_or_errors = find_roots_sturm(polynom, &mut 1e-6);
430 /// // Returns vector of roots or search errors;
431 ///
432 /// let roots: Vec<_> = find_roots_sturm(polynom, &mut 1e-8f64)
433 /// .iter()
434 /// .filter_map(|s| match s {
435 /// &Ok(ref x) => Some(*x),
436 /// &Err(_) => None,
437 /// })
438 /// .collect();
439 /// // Returns vector of roots filterin out all search errors;
440 /// ```
441 pub fn find_roots_sturm<F>(a: &[F], convergency: &mut dyn Convergency<F>) -> Vec<Result<F, SearchError>>
442 where
443 F: FloatType,
444 {
445 match a.len() {
446 0 => Vec::new(),
447 1 => find_roots_linear(F::one(), a[0]).as_ref().iter().map(|s| Ok(*s)).collect(),
448 2 => find_roots_quadratic(F::one(), a[0], a[1])
449 .as_ref()
450 .iter()
451 .map(|s| Ok(*s))
452 .collect(),
453 3 => find_roots_cubic(F::one(), a[0], a[1], a[2])
454 .as_ref()
455 .iter()
456 .map(|s| Ok(*s))
457 .collect(),
458 _ => {
459 let mut result = Vec::new();
460 let derivative_polynom = a.derivative_polynom();
461 match find_root_intervals(a, &derivative_polynom, convergency) {
462 Ok(root_intervals) => {
463 for root_interval in &root_intervals {
464 if let Ok(mut narrowed) = narrow_down(&root_interval, a, &derivative_polynom, convergency) {
465 result.push(a.find_root(&mut narrowed, convergency));
466 }
467 }
468 }
469 Err(error) => {
470 result.push(Err(error));
471 }
472 }
473 result
474 }
475 }
476 }
477
478 #[cfg(test)]
479 mod test {
480 use super::super::*;
481 use super::*;
482
483 #[test]
484 fn test_find_roots_sturm() {
485 let polynom = &[-2f64, 1f64];
486 let roots = find_roots_sturm(polynom, &mut 1e-6f64);
487 assert_eq!(roots, [Ok(1f64)]);
488 }
489
490 #[test]
491 fn test_polynom_value() {
492 let polynom = [1f64, -2f64, 1f64];
493 assert_eq!(1f64, polynom.value(&0f64));
494 assert_eq!(1f64, polynom.value(&1f64));
495 assert_eq!(3f64, polynom.value(&-1f64));
496 }
497
498 #[test]
499 fn test_polynom_value_and_derivative() {
500 let polynom = [1f64, -2f64, 1f64];
501 assert_eq!(
502 ValueAndDerivative {
503 value: Sample { x: 0f64, y: 1f64 },
504 derivative: -2f64
505 },
506 polynom.value_and_derivative(&0f64)
507 );
508 assert_eq!(
509 ValueAndDerivative {
510 value: Sample { x: 1f64, y: 1f64 },
511 derivative: 3f64
512 },
513 polynom.value_and_derivative(&1f64)
514 );
515 assert_eq!(
516 ValueAndDerivative {
517 value: Sample { x: -1f64, y: 3f64 },
518 derivative: -1f64
519 },
520 polynom.value_and_derivative(&-1f64)
521 );
522 }
523
524 #[test]
525 fn test_derivative_polynom_3() {
526 // x^3 + 1*x^2 - 2*x^1 + 1*x^0 => 3*x^2 + 2*x^1 - 2*x^0 => x^2 + (2/3)*x^1 - (2/3)*x^0
527 let polynom = [1f64, -2f64, 1f64];
528 let derivative = polynom.derivative_polynom();
529 assert_float_array_eq!(1e-15, derivative, [2f64 / 3f64, -2f64 / 3f64]);
530 }
531
532 #[test]
533 fn test_derivative_polynom_5() {
534 // x^5 - 2*x^4 - 3*x^3 + 4*x^2 + 0*x^1 + 0*x^0 => 5*x^4 - 8*x^3 - 9*x^2 + 8*x^1 + 0*x^0 => x^4 - (8/5)*x^3 - (9/5)*x^2 + (8/5)*x^1 + 0*x^0
535 let polynom = [-2f64, -3f64, 4f64, 0f64, 0f64];
536 let derivative = polynom.derivative_polynom();
537 assert_float_array_eq!(1e-15, derivative, [-8f64 / 5f64, -9f64 / 5f64, 8f64 / 5f64, 0f64]);
538 }
539
540 #[test]
541 fn find_roots_sturm_7() {
542 // x^7+4.0*x^6-4.0*x^4+2.0*x^3+1.0*x^2+6.0*x^1-3.0*x^0 => {-3.6547, -1.67175, 0.455904}
543 let polynom = [4f64, 0f64, -4f64, 2f64, 1f64, 6f64, -3f64];
544 let roots: Vec<_> = find_roots_sturm(&polynom, &mut 1e-8f64)
545 .iter()
546 .filter_map(|s| match s {
547 &Ok(ref x) => Some(*x),
548 &Err(_) => None,
549 })
550 .collect();
551 assert_float_array_eq!(1e-5, roots, [-3.6547f64, -1.67175f64, 0.455904f64]);
552 }
553
554 #[test]
555 fn find_roots_sturm_tim_lueke() {
556 // Try to find roots of the normalized quartic polynomial where the discriminant must be 0
557 // (as reported by Tim Lueke in December 2019)
558 // -14.0625*x^4-3.75*x^3+29.75*x^2+4.0*x^1-16.0*x^0 => {-1.1016116464173349, 0.9682783130840016}
559 let polynom = [
560 -3.75f64 / -14.0625f64,
561 29.75f64 / -14.0625f64,
562 4.0f64 / -14.0625f64,
563 -16.0f64 / -14.0625f64,
564 ];
565 let roots: Vec<_> = find_roots_sturm(&polynom, &mut 1e-8f64)
566 .iter()
567 .filter_map(|s| match s {
568 &Ok(ref x) => Some(*x),
569 &Err(_) => None,
570 })
571 .collect();
572
573 // these roots cannot be found
574 assert_float_array_eq!(1e-5, roots, []);
575 //assert_float_array_eq!(1e-5, roots, [-1.1016116464173349f64, 0.9682783130840016f64]);
576 }
577 }