rgsl/types/
series_acceleration.rs

1//
2// A rust binding for the GSL library by Guillaume Gomez (guillaume1.gomez@gmail.com)
3//
4
5/*!
6# Series Acceleration
7
8The functions described in this chapter accelerate the convergence of a series using the Levin u-transform. This method takes a small
9number of terms from the start of a series and uses a systematic approximation to compute an extrapolated value and an estimate of its
10error. The u-transform works for both convergent and divergent series, including asymptotic series.
11
12## Acceleration functions
13
14The following functions compute the full Levin u-transform of a series with its error estimate. The error estimate is computed by
15propagating rounding errors from each term through to the final extrapolation.
16
17These functions are intended for summing analytic series where each term is known to high accuracy, and the rounding errors are assumed
18to originate from finite precision. They are taken to be relative errors of order GSL_DBL_EPSILON for each term.
19
20The calculation of the error in the extrapolated value is an O(N^2) process, which is expensive in time and memory. A faster but less
21reliable method which estimates the error from the convergence of the extrapolated value is described in the next section. For the method
22described here a full table of intermediate values and derivatives through to O(N) must be computed and stored, but this does give a
23reliable error estimate.
24
25## Acceleration functions without error estimation
26
27The functions described in this section compute the Levin u-transform of series and attempt to estimate the error from the “truncation
28error” in the extrapolation, the difference between the final two approximations. Using this method avoids the need to compute an
29intermediate table of derivatives because the error is estimated from the behavior of the extrapolated value itself. Consequently this
30algorithm is an O(N) process and only requires O(N) terms of storage. If the series converges sufficiently fast then this procedure can
31be acceptable. It is appropriate to use this method when there is a need to compute many extrapolations of series with similar convergence
32properties at high-speed. For example, when numerically integrating a function defined by a parameterized series where the parameter
33varies only slightly. A reliable error estimate should be computed first using the full algorithm described above in order to verify the
34consistency of the results.
35
36## References and Further Reading
37
38The algorithms used by these functions are described in the following papers,
39
40T. Fessler, W.F. Ford, D.A. Smith, HURRY: An acceleration algorithm for scalar sequences and series ACM Transactions on Mathematical
41Software, 9(3):346–354, 1983. and Algorithm 602 9(3):355–357, 1983.
42
43The theory of the u-transform was presented by Levin,
44
45D. Levin, Development of Non-Linear Transformations for Improving Convergence of Sequences, Intern. J. Computer Math. B3:371–388, 1973.
46
47A review paper on the Levin Transform is available online,
48
49Herbert H. H. Homeier, Scalar Levin-Type Sequence Transformations, http://arxiv.org/abs/math/0005209.
50!*/
51
52use crate::Value;
53use ffi::FFI;
54
55ffi_wrapper!(
56    LevinUWorkspace,
57    *mut sys::gsl_sum_levin_u_workspace,
58    gsl_sum_levin_u_free,
59    "Workspace for Levin U Transform with error estimation."
60);
61
62impl LevinUWorkspace {
63    /// This function allocates a workspace for a Levin u-transform of n terms. The size of the workspace is O(2n^2 + 3n).
64    #[doc(alias = "gsl_sum_levin_u_alloc")]
65    pub fn new(n: usize) -> Option<LevinUWorkspace> {
66        let tmp = unsafe { sys::gsl_sum_levin_u_alloc(n) };
67
68        if tmp.is_null() {
69            None
70        } else {
71            Some(LevinUWorkspace::wrap(tmp))
72        }
73    }
74
75    /// This function takes the terms of a series in array of size array_size and computes the extrapolated limit of the series using a
76    /// Levin u-transform. Additional working space must be provided in w. The extrapolated sum is stored in sum_accel, with an estimate
77    /// of the absolute error stored in abserr. The actual term-by-term sum is returned in w->sum_plain. The algorithm calculates the
78    /// truncation error (the difference between two successive extrapolations) and round-off error (propagated from the individual terms)
79    /// to choose an optimal number of terms for the extrapolation. All the terms of the series passed in through array should be non-zero.
80    ///
81    /// Returns `(Value, sum_accel, abserr)`.
82    #[doc(alias = "gsl_sum_levin_u_accel")]
83    pub fn accel(&mut self, array: &[f64]) -> Result<(f64, f64), Value> {
84        let mut sum_accel = 0.;
85        let mut abserr = 0.;
86        let ret = unsafe {
87            sys::gsl_sum_levin_u_accel(
88                array.as_ptr(),
89                array.len() as _,
90                self.unwrap_unique(),
91                &mut sum_accel,
92                &mut abserr,
93            )
94        };
95        result_handler!(ret, (sum_accel, abserr))
96    }
97
98    pub fn sum_plain(&self) -> f64 {
99        unsafe { (*self.unwrap_shared()).sum_plain }
100    }
101
102    pub fn terms_used(&self) -> usize {
103        unsafe { (*self.unwrap_shared()).terms_used }
104    }
105
106    pub fn size(&self) -> usize {
107        unsafe { (*self.unwrap_shared()).size }
108    }
109}
110
111ffi_wrapper!(LevinUTruncWorkspace, *mut sys::gsl_sum_levin_utrunc_workspace, gsl_sum_levin_utrunc_free,
112"The following functions perform the same calculation without estimating the errors. They require
113`O(N)` storage instead of `O(N^2)`. This may be useful for summing many similar series where the
114size of the error has already been estimated reliably and is not expected to change.");
115
116impl LevinUTruncWorkspace {
117    /// This function allocates a workspace for a Levin u-transform of n terms, without error estimation. The size of the workspace is O(3n).
118    #[doc(alias = "gsl_sum_levin_utrunc_alloc")]
119    pub fn new(n: usize) -> Option<LevinUTruncWorkspace> {
120        let tmp = unsafe { sys::gsl_sum_levin_utrunc_alloc(n) };
121
122        if tmp.is_null() {
123            None
124        } else {
125            Some(LevinUTruncWorkspace::wrap(tmp))
126        }
127    }
128
129    /// This function takes the terms of a series in array of size array_size and computes the extrapolated limit of the series using a
130    /// Levin u-transform. Additional working space must be provided in w. The extrapolated sum is stored in sum_accel. The actual
131    /// term-by-term sum is returned in w->sum_plain. The algorithm terminates when the difference between two successive extrapolations
132    /// reaches a minimum or is sufficiently small. The difference between these two values is used as estimate of the error and is stored
133    /// in abserr_trunc. To improve the reliability of the algorithm the extrapolated values are replaced by moving averages when
134    /// calculating the truncation error, smoothing out any fluctuations.
135    ///
136    /// Returns `(Value, sum_accel, abserr_trunc)`.
137    #[doc(alias = "gsl_sum_levin_utrunc_accel")]
138    pub fn accel(&mut self, array: &[f64]) -> Result<(f64, f64), Value> {
139        let mut sum_accel = 0.;
140        let mut abserr_trunc = 0.;
141        let ret = unsafe {
142            sys::gsl_sum_levin_utrunc_accel(
143                array.as_ptr(),
144                array.len() as _,
145                self.unwrap_unique(),
146                &mut sum_accel,
147                &mut abserr_trunc,
148            )
149        };
150        result_handler!(ret, (sum_accel, abserr_trunc))
151    }
152
153    pub fn sum_plain(&self) -> f64 {
154        unsafe { (*self.unwrap_shared()).sum_plain }
155    }
156
157    pub fn terms_used(&self) -> usize {
158        unsafe { (*self.unwrap_shared()).terms_used }
159    }
160
161    pub fn size(&self) -> usize {
162        unsafe { (*self.unwrap_shared()).size }
163    }
164}