Special Functions

This example demonstrates special mathematical functions including Bessel functions and their applications.

Overview

Special functions are fundamental to many engineering applications:

  • Signal processing: Filter design and analysis

  • Electromagnetics: Waveguide mode calculations

  • Acoustics: Circular membrane vibrations

  • Optics: Diffraction patterns

Bessel Functions

First Kind (J_n)
  • Solutions to Bessel’s differential equation

  • Finite at the origin

  • Oscillatory behavior for positive arguments

Second Kind (Y_n)
  • Also called Neumann functions

  • Singular at the origin

  • Independent solution to Bessel’s equation

Key Properties
  • J_0(0) = 1, J_n(0) = 0 for n > 0

  • Recurrence relations connect different orders

  • Zeros are important for boundary value problems

Applications

Circular Drum Vibrations
  • Bessel function zeros determine mode frequencies

  • J_0 zeros: fundamental modes

  • Higher orders: more complex patterns

Cylindrical Waveguides
  • TE and TM mode cutoff frequencies

  • Field patterns in circular cross-section

  • Microwave and optical applications

Bessel Filters
  • Maximally flat group delay

  • Linear phase response

  • Named after Bessel functions

Boundary Value Problems
  • Heat conduction in cylinders

  • Electromagnetic fields

  • Quantum mechanics (spherical wells)

Bessel Zeros

The zeros of Bessel functions are critical values:

  • J_0 zeros: 2.405, 5.520, 8.654, 11.792, …

  • Used in filter design and mode analysis

  • Computed with bessel_zeros()

Code Highlights

The example demonstrates:

  • Bessel function evaluation with besselj() and bessely()

  • Multiple orders (J_0 through J_4)

  • Zero finding with bessel_zeros()

  • Visualization of function behavior

Source Code

  1"""
  2Demonstration of special functions and mathematical operations.
  3
  4This example shows:
  5- Bessel function computation and visualization
  6- Special function properties and characteristics
  7- Performance characteristics
  8"""
  9
 10from pathlib import Path
 11
 12import numpy as np
 13import plotly.graph_objects as go
 14from plotly.subplots import make_subplots
 15
 16from pytcl.mathematical_functions.special_functions import (
 17    bessel_zeros,
 18    besselj,
 19    bessely,
 20)
 21
 22SHOW_PLOTS = True
 23OUTPUT_DIR = Path("docs/_static/images/examples")
 24OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
 25
 26
 27def demo_bessel_functions() -> None:
 28    """Demonstrate Bessel functions of the first and second kind."""
 29    print("\n" + "=" * 60)
 30    print("Bessel Functions Demonstration")
 31    print("=" * 60)
 32
 33    # Compute Bessel functions over a range
 34    x = np.linspace(0.1, 10, 100)
 35
 36    # First kind - J_0 and J_1
 37    j0 = besselj(0, x)
 38    j1 = besselj(1, x)
 39
 40    # Second kind - Y_0 and Y_1
 41    y0 = bessely(0, x)
 42    y1 = bessely(1, x)
 43
 44    print(f"\nBessel Functions J_n and Y_n:")
 45    print(f"  J_0(1) = {besselj(0, 1.0):.6f}")
 46    print(f"  J_1(1) = {besselj(1, 1.0):.6f}")
 47    print(f"  Y_0(1) = {bessely(0, 1.0):.6f}")
 48    print(f"  Y_1(1) = {bessely(1, 1.0):.6f}")
 49
 50    fig = make_subplots(
 51        rows=1,
 52        cols=2,
 53        subplot_titles=(
 54            "Bessel Functions (First Kind)",
 55            "Bessel Functions (Second Kind)",
 56        ),
 57    )
 58
 59    # First kind
 60    fig.add_trace(
 61        go.Scatter(
 62            x=x,
 63            y=j0,
 64            mode="lines",
 65            name="J₀(x)",
 66            line=dict(color="blue", width=2),
 67            hovertemplate="<b>J₀(x)</b><br>x: %{x:.3f}<br>J₀(x): %{y:.6f}<extra></extra>",
 68        ),
 69        row=1,
 70        col=1,
 71    )
 72    fig.add_trace(
 73        go.Scatter(
 74            x=x,
 75            y=j1,
 76            mode="lines",
 77            name="J₁(x)",
 78            line=dict(color="red", width=2),
 79            hovertemplate="<b>J₁(x)</b><br>x: %{x:.3f}<br>J₁(x): %{y:.6f}<extra></extra>",
 80        ),
 81        row=1,
 82        col=1,
 83    )
 84
 85    # Second kind
 86    fig.add_trace(
 87        go.Scatter(
 88            x=x,
 89            y=y0,
 90            mode="lines",
 91            name="Y₀(x)",
 92            line=dict(color="blue", width=2),
 93            hovertemplate="<b>Y₀(x)</b><br>x: %{x:.3f}<br>Y₀(x): %{y:.6f}<extra></extra>",
 94        ),
 95        row=1,
 96        col=2,
 97    )
 98    fig.add_trace(
 99        go.Scatter(
100            x=x,
101            y=y1,
102            mode="lines",
103            name="Y₁(x)",
104            line=dict(color="red", width=2),
105            hovertemplate="<b>Y₁(x)</b><br>x: %{x:.3f}<br>Y₁(x): %{y:.6f}<extra></extra>",
106        ),
107        row=1,
108        col=2,
109    )
110
111    fig.update_xaxes(title_text="x", row=1, col=1)
112    fig.update_yaxes(title_text="Function Value", row=1, col=1)
113    fig.update_xaxes(title_text="x", row=1, col=2)
114    fig.update_yaxes(title_text="Function Value", row=1, col=2)
115
116    fig.update_layout(
117        height=500,
118        title_text="Bessel Functions of the First and Second Kind",
119        hovermode="x unified",
120        plot_bgcolor="rgba(240,240,240,0.5)",
121        showlegend=True,
122        legend=dict(x=0.02, y=0.98),
123    )
124
125    if SHOW_PLOTS:
126        fig.show()
127    else:
128        fig.write_html(str(OUTPUT_DIR / "special_functions_demo.html"))
129
130
131def demo_higher_order_bessel() -> None:
132    """Demonstrate higher order Bessel functions."""
133    print("\n" + "=" * 60)
134    print("Higher Order Bessel Functions")
135    print("=" * 60)
136
137    x = np.linspace(0.1, 10, 100)
138    x_val = 5.0
139
140    print(f"\nBessel functions at x={x_val}:")
141    for n in range(5):
142        j_n = besselj(n, x_val)
143        y_n = bessely(n, x_val)
144        print(f"  J_{n}({x_val}) = {j_n:.6f}, Y_{n}({x_val}) = {y_n:.6f}")
145
146    # Plot multiple orders
147    fig = go.Figure()
148
149    colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd"]
150    for n in range(5):
151        jn_vals = besselj(n, x)
152        fig.add_trace(
153            go.Scatter(
154                x=x,
155                y=jn_vals,
156                mode="lines",
157                name=f"J_{n}(x)",
158                line=dict(width=2.5, color=colors[n]),
159                hovertemplate=f"<b>J_{n}(x)</b><br>x: %{{x:.3f}}<br>J_{n}(x): %{{y:.6f}}<extra></extra>",
160            )
161        )
162
163    fig.update_layout(
164        title="Bessel Functions of Different Orders",
165        xaxis_title="x",
166        yaxis_title="J_n(x)",
167        height=500,
168        hovermode="x unified",
169        plot_bgcolor="rgba(240,240,240,0.5)",
170        showlegend=True,
171        legend=dict(x=0.65, y=0.95),
172    )
173
174    if SHOW_PLOTS:
175        fig.show()
176    else:
177        fig.write_html(str(OUTPUT_DIR / "special_functions_demo_higher_order.html"))
178
179
180def demo_bessel_zeros() -> None:
181    """Demonstrate Bessel function zeros and roots."""
182    print("\n" + "=" * 60)
183    print("Bessel Function Zeros")
184    print("=" * 60)
185
186    print(f"\nZeros of Bessel functions are important for:")
187    print(f"  - Circular drum vibrations")
188    print(f"  - Cylindrical waveguides")
189    print(f"  - Bessel filter design")
190    print(f"  - Boundary value problems")
191
192    # Get zeros of J_0
193    zeros = bessel_zeros(0, 5)
194    print(f"\nFirst 5 zeros of J_0(x): {zeros}")
195
196
197def main() -> None:
198    """Run all demonstrations."""
199    print("\n" + "=" * 60)
200    print("Mathematical Special Functions Demonstration")
201    print("=" * 60)
202
203    demo_bessel_functions()
204    demo_higher_order_bessel()
205    demo_bessel_zeros()
206
207    print("\n" + "=" * 60)
208    print("Demonstration Complete")
209    print("=" * 60)
210
211
212if __name__ == "__main__":
213    main()
214
215OUTPUT_DIR = Path("docs/_static/images/examples")
216OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
217
218SHOW_PLOTS = True

Running the Example

python examples/special_functions_demo.py

See Also