Bessel Functions Example

Demonstrates Bessel functions of the first and second kind using specialfunctions.bessel_j0(), specialfunctions.bessel_j1(), specialfunctions.bessel_jn(), specialfunctions.bessel_y0(), and specialfunctions.bessel_y1().

Example Code

"""Example: IMSL Special Functions — Bessel functions."""
from __future__ import annotations

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from specialfunctions import bessel_j0, bessel_j1, bessel_jn, bessel_y0, bessel_y1

x = np.linspace(0.01, 20, 800)
x_pos = np.linspace(0.1, 20, 800)

print(f"J0(0) = {bessel_j0(0.0):.6f}  (expected: 1.0)")
print(f"J1(0) = {bessel_j1(0.0):.6f}  (expected: 0.0)")
print(f"J0(2.4048) ≈ {bessel_j0(2.4048):.6f}  (≈ 0, first zero of J0)")
print(f"Y0(1) = {bessel_y0(1.0):.6f}")
print(f"Y1(1) = {bessel_y1(1.0):.6f}")

fig, axes = plt.subplots(1, 2, figsize=(14, 5))
fig.suptitle("Bessel Functions", fontsize=14)

axes[0].plot(x, bessel_j0(x), label="J₀(x)", lw=1.5)
axes[0].plot(x, bessel_j1(x), label="J₁(x)", lw=1.5)
axes[0].plot(x, bessel_jn(2, x), label="J₂(x)", lw=1.5)
axes[0].axhline(0, color="k", lw=0.5, ls="--")
axes[0].set_title("Bessel Functions of the First Kind")
axes[0].set_xlabel("x")
axes[0].legend()
axes[0].grid(True, alpha=0.3)

axes[1].plot(x_pos, bessel_y0(x_pos), label="Y₀(x)", lw=1.5)
axes[1].plot(x_pos, bessel_y1(x_pos), label="Y₁(x)", lw=1.5)
axes[1].set_ylim(-3, 1)
axes[1].axhline(0, color="k", lw=0.5, ls="--")
axes[1].set_title("Bessel Functions of the Second Kind")
axes[1].set_xlabel("x")
axes[1].legend()
axes[1].grid(True, alpha=0.3)

plt.tight_layout()
plt.savefig("test_output/example_imsl_bessel_functions.svg", bbox_inches="tight")
print("Saved: test_output/example_imsl_bessel_functions.svg")

Plot Output

Bessel function plots

Bessel functions J0, J1, J2 (first kind) and Y0, Y1 (second kind) plotted over their domains.

Console Output

J0(0) = 1.000000  (expected: 1.0)
J1(0) = 0.000000  (expected: 0.0)
Traceback (most recent call last):
  File "E:\ITDS\itds\packages\specialfunctions\examples\example_imsl_bessel_functions.py", line 15, in <module>
    print(f"J0(2.4048) \u2248 {bessel_j0(2.4048):.6f}  (\u2248 0, first zero of J0)")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.2800.0_x64__qbz5n2kfra8p0\Lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'charmap' codec can't encode character '\u2248' in position 11: character maps to <undefined>