Skip to main content

lib_jsl_integration/
complex_path_integrals.rs

1//! Contour integrals `∫ f(z) dz` of complex functions along paths in the complex plane.
2//!
3//! A path is a [`Contour`]: a chain of [`PathSegment`]s (straight lines, circular arcs, or any
4//! smooth parametrised curve). Each segment is integrated as `∫ f(z(t)) z'(t) dt` with an adaptive
5//! 15-point Gauss-Kronrod rule applied to the complex integrand, with the Gauss 7-point rule giving
6//! the error estimate.
7//!
8//! On top of that are the standard tools of complex analysis: [`residue`], the Cauchy formula for
9//! derivatives [`cauchy_derivative`], and the [`winding_number`] of a closed path around a point.
10//!
11//! See the book entry [Complex contour integration](https://jwkunz.github.io/lib_jsl/book/integration/contour-integration.html).
12
13use crate::adaptive_gl7k15_integration_engine::{GAUSS_LEGENDRE_WEIGHTS_7, KRONROD_NODES_15, KRONROD_WEIGHTS_15};
14use lib_jsl_core::ErrorsJSL;
15use num_complex::Complex;
16use std::f64::consts::TAU;
17use std::fmt;
18use std::rc::Rc;
19
20/// A double-precision complex number.
21pub type C64 = Complex<f64>;
22
23/// One smooth piece of a contour.
24#[derive(Clone)]
25pub enum PathSegment {
26    /// The straight segment from `from` to `to`.
27    Line { from: C64, to: C64 },
28    /// The circular arc `centre + radius·e^{iθ}` for `θ` from `start_angle` to `end_angle`
29    /// (radians; counter-clockwise when `end_angle > start_angle`).
30    Arc { centre: C64, radius: f64, start_angle: f64, end_angle: f64 },
31    /// A parametrised curve `z(t)` for `t` in `[t0, t1]` with derivative `dz(t)`.
32    Curve { z: Rc<dyn Fn(f64) -> C64>, dz: Rc<dyn Fn(f64) -> C64>, t0: f64, t1: f64 },
33}
34
35impl fmt::Debug for PathSegment {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match self {
38            PathSegment::Line { from, to } => write!(f, "Line({from} -> {to})"),
39            PathSegment::Arc { centre, radius, start_angle, end_angle } => write!(f, "Arc(centre {centre}, r {radius}, {start_angle}..{end_angle})"),
40            PathSegment::Curve { t0, t1, .. } => write!(f, "Curve(t {t0}..{t1})"),
41        }
42    }
43}
44
45impl PathSegment {
46    /// The straight segment from `from` to `to`.
47    pub fn line(from: C64, to: C64) -> Self {
48        PathSegment::Line { from, to }
49    }
50
51    /// The full counter-clockwise circle, starting and ending at angle `0`.
52    pub fn circle(centre: C64, radius: f64) -> Self {
53        PathSegment::Arc { centre, radius, start_angle: 0.0, end_angle: TAU }
54    }
55
56    /// The circular arc `centre + radius·e^{iθ}`, `θ` from `start_angle` to `end_angle` (radians).
57    pub fn arc(centre: C64, radius: f64, start_angle: f64, end_angle: f64) -> Self {
58        PathSegment::Arc { centre, radius, start_angle, end_angle }
59    }
60
61    /// The curve `z(t)`, `t` from `t0` to `t1`, with its derivative `dz(t) = z'(t)`.
62    pub fn curve(z: impl Fn(f64) -> C64 + 'static, dz: impl Fn(f64) -> C64 + 'static, t0: f64, t1: f64) -> Self {
63        PathSegment::Curve { z: Rc::new(z), dz: Rc::new(dz), t0, t1 }
64    }
65
66    /// The segment's parameter interval.
67    fn interval(&self) -> (f64, f64) {
68        match self {
69            PathSegment::Line { .. } => (0.0, 1.0),
70            PathSegment::Arc { start_angle, end_angle, .. } => (*start_angle, *end_angle),
71            PathSegment::Curve { t0, t1, .. } => (*t0, *t1),
72        }
73    }
74
75    /// The point `z(t)` and velocity `z'(t)` at parameter `t`.
76    fn eval(&self, t: f64) -> (C64, C64) {
77        match self {
78            PathSegment::Line { from, to } => (from + (to - from) * t, to - from),
79            PathSegment::Arc { centre, radius, .. } => {
80                let e = C64::from_polar(1.0, t);
81                (centre + e * *radius, C64::new(0.0, 1.0) * e * *radius)
82            }
83            PathSegment::Curve { z, dz, .. } => (z(t), dz(t)),
84        }
85    }
86
87    /// The first point of the segment.
88    pub fn start(&self) -> C64 {
89        self.eval(self.interval().0).0
90    }
91
92    /// The last point of the segment.
93    pub fn end(&self) -> C64 {
94        self.eval(self.interval().1).0
95    }
96
97    /// The point at fraction `s` in `[0, 1]` of the parameter range.
98    pub fn point_at(&self, s: f64) -> C64 {
99        let (a, b) = self.interval();
100        self.eval(a + s * (b - a)).0
101    }
102}
103
104/// A path made of consecutive segments.
105#[derive(Debug, Clone, Default)]
106pub struct Contour {
107    pub segments: Vec<PathSegment>,
108}
109
110impl Contour {
111    /// The contour through the given segments, in order.
112    pub fn new(segments: Vec<PathSegment>) -> Self {
113        Contour { segments }
114    }
115
116    /// The polyline through `vertices` (closed back to the first vertex when `closed`).
117    pub fn polyline(vertices: &[C64], closed: bool) -> Self {
118        let n = vertices.len();
119        let count = if closed { n } else { n.saturating_sub(1) };
120        Contour { segments: (0..count).map(|i| PathSegment::line(vertices[i], vertices[(i + 1) % n])).collect() }
121    }
122
123    /// The counter-clockwise circle about `centre`.
124    pub fn circle(centre: C64, radius: f64) -> Self {
125        Contour { segments: vec![PathSegment::circle(centre, radius)] }
126    }
127
128    /// The axis-aligned rectangle with opposite corners `lower_left` and `upper_right`, traversed
129    /// counter-clockwise.
130    pub fn rectangle(lower_left: C64, upper_right: C64) -> Self {
131        let (a, c) = (lower_left, upper_right);
132        Self::polyline(&[a, C64::new(c.re, a.im), c, C64::new(a.re, c.im)], true)
133    }
134
135    /// Appends another contour's segments.
136    pub fn then(mut self, other: Contour) -> Self {
137        self.segments.extend(other.segments);
138        self
139    }
140
141    /// Whether each segment starts where the previous one ends (within `tol`).
142    pub fn is_connected(&self, tol: f64) -> bool {
143        self.segments.windows(2).all(|w| (w[0].end() - w[1].start()).norm() <= tol)
144    }
145
146    /// Whether the contour is connected and returns to its starting point (within `tol`).
147    pub fn is_closed(&self, tol: f64) -> bool {
148        match (self.segments.first(), self.segments.last()) {
149            (Some(first), Some(last)) => self.is_connected(tol) && (last.end() - first.start()).norm() <= tol,
150            _ => false,
151        }
152    }
153
154    /// The arc length (adaptively integrated `|z'(t)|`).
155    pub fn length(&self) -> f64 {
156        self.segments.iter().map(|s| integrate_segment(&|_, dz| C64::new(dz.norm(), 0.0), s, 1e-12, true).0.re).sum()
157    }
158}
159
160/// The result of a contour integral.
161#[derive(Debug, Clone, Copy, PartialEq)]
162pub struct PathIntegral {
163    pub value: C64,
164    /// An estimate of the absolute error (sum of the Gauss/Kronrod differences).
165    pub error: f64,
166    /// Number of integrand evaluations.
167    pub nfev: usize,
168}
169
170/// The 7-point Gauss and 15-point Kronrod estimates of `∫ₐᵇ f`, and the Kronrod estimate of
171/// `∫ₐᵇ |f|`.
172fn gk15(f: &mut impl FnMut(f64) -> C64, a: f64, b: f64) -> (C64, C64, f64) {
173    let (centre, half) = (0.5 * (a + b), 0.5 * (b - a));
174    let mut kronrod = C64::new(0.0, 0.0);
175    let mut gauss = C64::new(0.0, 0.0);
176    let mut absolute = 0.0;
177    for (i, (&x, &wk)) in KRONROD_NODES_15.iter().zip(&KRONROD_WEIGHTS_15).enumerate() {
178        let (sample, magnitude) = if i == 0 {
179            let v = f(centre);
180            (v, v.norm())
181        } else {
182            let (lo, hi) = (f(centre - half * x), f(centre + half * x));
183            (lo + hi, lo.norm() + hi.norm())
184        };
185        kronrod += sample * wk;
186        absolute += magnitude * wk;
187        // The even-indexed Kronrod nodes (centre first) coincide with the 7-point Gauss nodes.
188        if i % 2 == 0 {
189            gauss += sample * GAUSS_LEGENDRE_WEIGHTS_7[i / 2];
190        }
191    }
192    (gauss * half, kronrod * half, absolute * half.abs())
193}
194
195/// Integrates `weight(z(t), z'(t))` over the segment's parameter range (`weight = f(z) z'` for a
196/// contour integral, `|z'|` for arc length).
197/// Returns the value, the error estimate, the number of evaluations, and whether the tolerance
198/// was met (panels accepted only because of the depth or evaluation limits, with a total error
199/// well above the tolerance, mean it was not).
200fn integrate_segment(weight: &dyn Fn(C64, C64) -> C64, seg: &PathSegment, tol: f64, absolute: bool) -> (C64, f64, usize, bool) {
201    let (a, b) = seg.interval();
202    let evals = std::cell::Cell::new(0usize);
203    let mut integrand = |t: f64| {
204        evals.set(evals.get() + 1);
205        let (z, dz) = seg.eval(t);
206        weight(z, dz)
207    };
208    // Stack-based adaptive bisection: each interval is accepted when its error is within its
209    // share of the tolerance (proportional to its width). The segment starts as four panels, so
210    // that an integrand oscillating several times along it (e^z/z^13 around a circle, say) is not
211    // aliased by a single 15-point rule into a wrong answer that looks converged.
212    let total_width = (b - a).abs();
213    const INITIAL_PANELS: usize = 4;
214    let mut stack: Vec<(f64, f64, usize)> = (0..INITIAL_PANELS)
215        .map(|i| (a + (b - a) * i as f64 / INITIAL_PANELS as f64, a + (b - a) * (i + 1) as f64 / INITIAL_PANELS as f64, 0))
216        .collect();
217    let (mut value, mut error) = (C64::new(0.0, 0.0), 0.0);
218    let mut forced = false;
219    // A relative tolerance is measured against ∫|f(z) z'| dt, the scale that rounding errors in the
220    // sum are proportional to: the integral itself may be far smaller through cancellation.
221    let mut magnitude = 0.0;
222    for &(lo, hi, _) in &stack {
223        let (_, k, m) = gk15(&mut integrand, lo, hi);
224        if !k.re.is_finite() || !k.im.is_finite() {
225            // The integrand blew up (for example a path through a pole): bisecting cannot help.
226            return (C64::new(f64::NAN, f64::NAN), f64::NAN, evals.get(), false);
227        }
228        magnitude += m;
229    }
230    let scale = if absolute { 1.0 } else { magnitude.max(1e-300) };
231    const MAX_EVALUATIONS: usize = 2_000_000;
232    while let Some((lo, hi, depth)) = stack.pop() {
233        let (g, k, _) = gk15(&mut integrand, lo, hi);
234        let err = (k - g).norm();
235        let allowed = tol * scale * if total_width > 0.0 { (hi - lo).abs() / total_width } else { 1.0 };
236        // Accept when within tolerance; also when out of budget or refined past useful precision,
237        // or when the estimate is not finite (a singular sub-interval), where more splitting is futile.
238        if err <= allowed || depth >= 40 || evals.get() > MAX_EVALUATIONS || !err.is_finite() {
239            forced |= err > allowed || !err.is_finite();
240            value += k;
241            error += err;
242        } else {
243            let mid = 0.5 * (lo + hi);
244            stack.push((lo, mid, depth + 1));
245            stack.push((mid, hi, depth + 1));
246        }
247    }
248    let converged = !forced || error <= 10.0 * tol * scale;
249    (value, error, evals.get(), converged)
250}
251
252/// Integrates `f` along the contour to relative tolerance `tol` (for example `1e-10`) per segment,
253/// relative to `∫|f(z)| |dz|` along the segment (the smallest error floating point can promise when
254/// the integral is small through cancellation).
255pub fn contour_integral(f: impl Fn(C64) -> C64, contour: &Contour, tol: f64) -> Result<PathIntegral, ErrorsJSL> {
256    if contour.segments.is_empty() {
257        return Err(ErrorsJSL::InvalidInputRange("The contour has no segments."));
258    }
259    if tol.is_nan() || tol <= 0.0 {
260        return Err(ErrorsJSL::InvalidInputRange("The tolerance must be positive."));
261    }
262    let mut total = PathIntegral { value: C64::new(0.0, 0.0), error: 0.0, nfev: 0 };
263    for seg in &contour.segments {
264        let (v, e, n, converged) = integrate_segment(&|z, dz| f(z) * dz, seg, tol, false);
265        if !converged {
266            return Err(ErrorsJSL::RuntimeError("The integral did not converge (the path may pass through or very near a singularity)."));
267        }
268        total.value += v;
269        total.error += e;
270        total.nfev += n;
271    }
272    if !total.value.re.is_finite() || !total.value.im.is_finite() {
273        return Err(ErrorsJSL::RuntimeError("The integral is not finite (the path may pass through a singularity)."));
274    }
275    Ok(total)
276}
277
278/// The integral along the polyline through `vertices` (open).
279pub fn polyline_integral(f: impl Fn(C64) -> C64, vertices: &[C64], tol: f64) -> Result<PathIntegral, ErrorsJSL> {
280    contour_integral(f, &Contour::polyline(vertices, false), tol)
281}
282
283/// The residue of `f` at `z0`: `(1/2πi) ∮ f(z) dz` over a counter-clockwise circle of the given
284/// `radius`. The circle must enclose `z0` and no other singularity of `f`.
285pub fn residue(f: impl Fn(C64) -> C64, z0: C64, radius: f64, tol: f64) -> Result<C64, ErrorsJSL> {
286    if radius.is_nan() || radius <= 0.0 {
287        return Err(ErrorsJSL::InvalidInputRange("The radius must be positive."));
288    }
289    let r = contour_integral(f, &Contour::circle(z0, radius), tol)?;
290    Ok(r.value / C64::new(0.0, TAU))
291}
292
293/// The `n`-th derivative `f⁽ⁿ⁾(z0)` of an analytic function by Cauchy's integral formula,
294/// `n!/(2πi) ∮ f(z)/(z - z0)^{n+1} dz`, over a circle of the given `radius` inside the region
295/// where `f` is analytic.
296pub fn cauchy_derivative(f: impl Fn(C64) -> C64, z0: C64, n: u32, radius: f64, tol: f64) -> Result<C64, ErrorsJSL> {
297    if radius.is_nan() || radius <= 0.0 {
298        return Err(ErrorsJSL::InvalidInputRange("The radius must be positive."));
299    }
300    let r = contour_integral(|z| f(z) / (z - z0).powi(n as i32 + 1), &Contour::circle(z0, radius), tol)?;
301    let factorial: f64 = (1..=n).map(f64::from).product();
302    Ok(r.value * factorial / C64::new(0.0, TAU))
303}
304
305/// The winding number of a closed polygon (vertices in order, implicitly closed) around `point`:
306/// positive for counter-clockwise loops. Computed from the accumulated change of argument, so it
307/// is exact for any simple or self-intersecting polygon. `None` if `point` lies on the boundary.
308pub fn winding_number(vertices: &[C64], point: C64) -> Option<i32> {
309    let n = vertices.len();
310    if n < 3 {
311        return Some(0);
312    }
313    let mut total = 0.0;
314    for i in 0..n {
315        let (a, b) = (vertices[i] - point, vertices[(i + 1) % n] - point);
316        if a.norm() == 0.0 || b.norm() == 0.0 || (a.re * b.im - a.im * b.re).abs() <= 1e-14 * a.norm() * b.norm() && a.re * b.re + a.im * b.im < 0.0 {
317            return None; // vertex or edge passes through the point
318        }
319        total += (a.re * b.im - a.im * b.re).atan2(a.re * b.re + a.im * b.im);
320    }
321    Some((total / TAU).round() as i32)
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327    use std::f64::consts::PI;
328
329    fn close(a: C64, b: C64, tol: f64) -> bool {
330        (a - b).norm() < tol
331    }
332
333    #[test]
334    fn integral_of_one_over_z_around_the_unit_circle() {
335        let r = contour_integral(|z| z.inv(), &Contour::circle(C64::new(0.0, 0.0), 1.0), 1e-12).unwrap();
336        assert!(close(r.value, C64::new(0.0, TAU), 1e-10), "{:?}", r);
337        assert!(r.error < 1e-9);
338        // Off-centre circle that still encloses the origin, and one that does not.
339        let enclosing = contour_integral(|z| z.inv(), &Contour::circle(C64::new(0.5, 0.0), 1.0), 1e-12).unwrap();
340        assert!(close(enclosing.value, C64::new(0.0, TAU), 1e-9));
341        let outside = contour_integral(|z| z.inv(), &Contour::circle(C64::new(3.0, 0.0), 1.0), 1e-12).unwrap();
342        assert!(outside.value.norm() < 1e-10);
343    }
344
345    #[test]
346    fn analytic_functions_are_path_independent() {
347        let f = |z: C64| z * z + z.exp();
348        let antiderivative = |z: C64| z * z * z / 3.0 + z.exp();
349        let (a, b) = (C64::new(0.0, 0.0), C64::new(1.0, 2.0));
350        let want = antiderivative(b) - antiderivative(a);
351        let straight = contour_integral(f, &Contour::new(vec![PathSegment::line(a, b)]), 1e-12).unwrap();
352        let dog_leg = polyline_integral(f, &[a, C64::new(2.0, -1.0), b], 1e-12).unwrap();
353        let arc = Contour::new(vec![PathSegment::line(a, C64::new(0.0, 2.0)), PathSegment::line(C64::new(0.0, 2.0), b)]);
354        let via_arc = contour_integral(f, &arc, 1e-12).unwrap();
355        for r in [straight, dog_leg, via_arc] {
356            assert!(close(r.value, want, 1e-9), "{:?} vs {want}", r.value);
357        }
358        // Closed contour integral of an analytic function vanishes.
359        let closed = contour_integral(f, &Contour::rectangle(C64::new(-1.0, -1.0), C64::new(2.0, 1.5)), 1e-12).unwrap();
360        assert!(closed.value.norm() < 1e-9);
361    }
362
363    #[test]
364    fn powers_around_a_circle_and_curves() {
365        // ∮ z^n dz = 2πi for n = -1 and 0 otherwise.
366        for n in [-3, -2, 0, 1, 4] {
367            let r = contour_integral(|z| z.powi(n), &Contour::circle(C64::new(0.0, 0.0), 2.0), 1e-12).unwrap();
368            assert!(r.value.norm() < 1e-9, "n={n}");
369        }
370        // The same circle as a generic parametrised curve.
371        let curve = PathSegment::curve(|t| C64::from_polar(2.0, t), |t| C64::new(0.0, 1.0) * C64::from_polar(2.0, t), 0.0, TAU);
372        let r = contour_integral(|z| z.inv(), &Contour::new(vec![curve]), 1e-12).unwrap();
373        assert!(close(r.value, C64::new(0.0, TAU), 1e-10));
374        // Length of a circle and of a polyline.
375        assert!((Contour::circle(C64::new(1.0, 1.0), 3.0).length() - 6.0 * PI).abs() < 1e-9);
376        assert!((Contour::polyline(&[C64::new(0.0, 0.0), C64::new(3.0, 4.0)], false).length() - 5.0).abs() < 1e-10);
377    }
378
379    #[test]
380    fn residues_and_the_residue_theorem() {
381        // 1/(z²+1) has residue 1/(2i) = -i/2 at i and +i/2 at -i.
382        let f = |z: C64| (z * z + 1.0).inv();
383        let at_i = residue(f, C64::new(0.0, 1.0), 0.5, 1e-12).unwrap();
384        assert!(close(at_i, C64::new(0.0, -0.5), 1e-10));
385        let at_minus_i = residue(f, C64::new(0.0, -1.0), 0.5, 1e-12).unwrap();
386        assert!(close(at_minus_i, C64::new(0.0, 0.5), 1e-10));
387        // A contour around both poles gives 2πi times the sum of residues (zero here).
388        let both = contour_integral(f, &Contour::rectangle(C64::new(-2.0, -2.0), C64::new(2.0, 2.0)), 1e-12).unwrap();
389        assert!(both.value.norm() < 1e-9);
390        // A double pole: e^z / z² has residue 1 at 0; sin z / z³ has residue 0 (and e^z / z³ has 1/2).
391        assert!(close(residue(|z| z.exp() / (z * z), C64::new(0.0, 0.0), 1.0, 1e-12).unwrap(), C64::new(1.0, 0.0), 1e-10));
392        assert!(close(residue(|z| z.exp() / (z * z * z), C64::new(0.0, 0.0), 1.0, 1e-12).unwrap(), C64::new(0.5, 0.0), 1e-10));
393        assert!(residue(f, C64::new(0.0, 1.0), -1.0, 1e-9).is_err());
394    }
395
396    #[test]
397    fn cauchy_formula_for_derivatives() {
398        let z0 = C64::new(0.3, -0.2);
399        for n in 0..5 {
400            let d = cauchy_derivative(|z| z.exp(), z0, n, 1.0, 1e-12).unwrap();
401            assert!(close(d, z0.exp(), 1e-9), "n={n}");
402        }
403        // e^z/z^13 oscillates 13 times around the circle; a single 15-point panel used to alias
404        // it into a wrong answer that looked converged (error ≈ 1 at radius 2.5). Radii below about
405        // 3 are limited by rounding instead (see the book figure).
406        for r in [3.0, 6.0, 10.0] {
407            let d = cauchy_derivative(|z| z.exp(), C64::new(0.0, 0.0), 12, r, 1e-14).unwrap();
408            assert!(close(d, C64::new(1.0, 0.0), 1e-9), "r={r}: {d}");
409        }
410        // d²/dz² of z⁵ at 2 is 20·8 = 160.
411        assert!(close(cauchy_derivative(|z| z.powi(5), C64::new(2.0, 0.0), 2, 0.5, 1e-12).unwrap(), C64::new(160.0, 0.0), 1e-8));
412    }
413
414    #[test]
415    fn winding_numbers_and_contour_properties() {
416        let square = [C64::new(-1.0, -1.0), C64::new(1.0, -1.0), C64::new(1.0, 1.0), C64::new(-1.0, 1.0)];
417        assert_eq!(winding_number(&square, C64::new(0.0, 0.0)), Some(1));
418        assert_eq!(winding_number(&square, C64::new(3.0, 0.0)), Some(0));
419        let reversed: Vec<C64> = square.iter().rev().copied().collect();
420        assert_eq!(winding_number(&reversed, C64::new(0.2, 0.1)), Some(-1));
421        assert_eq!(winding_number(&square, C64::new(1.0, 0.0)), None); // on an edge
422        assert_eq!(winding_number(&square, C64::new(1.0, 1.0)), None); // on a vertex
423        // A figure that loops twice winds twice.
424        let twice: Vec<C64> = (0..16).map(|k| C64::from_polar(1.0, TAU * 2.0 * k as f64 / 16.0)).collect();
425        assert_eq!(winding_number(&twice, C64::new(0.0, 0.0)), Some(2));
426        let c = Contour::rectangle(C64::new(0.0, 0.0), C64::new(1.0, 1.0));
427        assert!(c.is_closed(1e-12) && Contour::polyline(&square, false).is_connected(1e-12) && !Contour::polyline(&square, false).is_closed(1e-12));
428        assert!(Contour::default().segments.is_empty() && !Contour::default().is_closed(1e-12));
429    }
430
431    #[test]
432    fn error_handling() {
433        assert!(contour_integral(|z| z, &Contour::default(), 1e-9).is_err());
434        assert!(contour_integral(|z| z, &Contour::circle(C64::new(0.0, 0.0), 1.0), 0.0).is_err());
435        // A path straight through a pole is reported rather than returning garbage.
436        let through_pole = Contour::new(vec![PathSegment::line(C64::new(-1.0, 0.0), C64::new(1.0, 0.0))]);
437        assert!(contour_integral(|z| z.inv(), &through_pole, 1e-9).is_err());
438        let arc = Contour::new(vec![PathSegment::arc(C64::new(0.0, 0.0), 1.0, 0.0, PI)]);
439        let half = contour_integral(|z| z.inv(), &arc, 1e-12).unwrap();
440        assert!(close(half.value, C64::new(0.0, PI), 1e-10));
441    }
442}