### Doubly-Infinite Integral with QuadGK Source: https://context7.com/juliamath/quadgk.jl/llms.txt Calculates a doubly-infinite integral. This example demonstrates the integration of the Gaussian function over the entire real line. ```julia # Doubly-infinite integral: Gaussian integral = √π I, E = quadgk(x -> exp(-x^2), -Inf, Inf) # I ≈ 1.7724538509055137 ``` -------------------------------- ### Contour Integration using Parameterization Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Perform contour integration by parameterizing the contour and converting it to a real integral. This example integrates cos(z)/z around a circle. ```julia-repl julia> quadgk(ϕ -> cos(cis(ϕ)) * im, 0, 2π) (0.0 + 6.283185307179586im, 1.8649646913725044e-8) ``` -------------------------------- ### Rescale Kronrod Quadrature Rule Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Rescales a Kronrod quadrature rule from the interval (-1,1) to a new interval (4,7) using the `kronrod` function. This example shows how to generate a higher-order rule with interval rescaling and custom weights. ```julia-repl julia> x, w = kronrod(JholloW(9), 5, 3, (-1,1) => (4,7)); [x w] 11×2 Matrix{Float64}: 4.02387 0.0638731 4.14073 0.17285 4.36875 0.280201 4.6923 0.361561 5.08055 0.409275 5.5 0.424481 5.91945 0.409275 6.3077 0.361561 6.63125 0.280201 6.85927 0.17285 6.97613 0.0638731 ``` -------------------------------- ### Richardson Extrapolation for Conditionally Convergent Integrals Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Uses the Richardson.jl package to numerically compute the limit of a Laplace transform, effectively handling a conditionally convergent integral. Requires the Richardson package to be installed. ```julia-repl julia> using Richardson julia> extrapolate(1, rtol=1e-8) do s quadgk(x -> exp(-s*x) * sin(x)/x, 0, Inf, rtol=1e-10)[1] end (1.5707963268036178, 4.397326947014335e-11) ``` -------------------------------- ### Comparison of Integration Methods Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Compares the results and performance of the slow (direct) and fast (singularity-subtracted) methods for integrating a nearly singular function. Demonstrates the significant reduction in function evaluations achieved by the fast method. ```julia-repl julia> int_slow(cos, 1e-6, -1, 1) (1.1102230246251565e-16 + 3.1415896808206125im, 1.4895091715264936e-9, 1230) julia> int_fast(cos, 1e-6, -1, 1) (3.3306690738754696e-16 + 3.1415896808190418im, 1.8459683038047577e-12, 31) ``` -------------------------------- ### Integrate Vector-Valued Function Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Integrates a function that returns a vector. The error estimate is a bound on the norm of the error vector. This example shows the default Euclidean norm. ```julia-repl julia> quadgk(x -> [1,x,x^2,x^3], 0, 1) ([1.0, 0.5, 0.3333333333333333, 0.25], 6.206335383118183e-17) ``` -------------------------------- ### Vectorized Integration with BatchIntegrand Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md For integrands that can process multiple points simultaneously, use the `BatchIntegrand` wrapper with `quadgk`. This requires pre-allocated input and output buffers for efficiency. ```julia QuadGK.BatchIntegrand ``` -------------------------------- ### QuadGK Variants for Integration Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md Choose from variants like `quadgk_count` to get integrand evaluation counts, `quadgk_print` to see intermediate evaluations, or `quadgk!` for an in-place API suitable for array-valued functions. ```julia QuadGK.quadgk_count ``` ```julia QuadGK.quadgk_print ``` ```julia QuadGK.quadgk! ``` -------------------------------- ### Construct Unweighted Gauss and Kronrod Rules Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md Generate standard Gauss or Gauss–Kronrod quadrature rules for integrals from -1 to 1 or a to b. Specify the floating-point type and the number of points for the rule. ```julia QuadGK.gauss(::Type{<:AbstractFloat}, ::Integer) ``` ```julia QuadGK.kronrod(::Type{<:AbstractFloat}, ::Integer) ``` -------------------------------- ### Integration with Evaluation Tracing using QuadGK_print Source: https://context7.com/juliamath/quadgk.jl/llms.txt Performs integration and prints each integrand evaluation to standard output. Useful for pedagogical purposes and debugging the integration process. ```julia using QuadGK ``` -------------------------------- ### Gauss-Jacobi (7-point) vs. Exact Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Demonstrates the accuracy of a 7-point Gauss-Jacobi quadrature rule for integrating cos(2x), achieving 10 digits of accuracy. This highlights the rapid convergence of Gaussian quadrature for smooth functions. ```julia-repl julia> x, w = gauss(FastGaussQuadrature.jacobi_jacobimatrix(7, α, β), I₁); julia> I = sum(@. cos(2x) * w) 0.9016684424777912 julia> I - exact 2.522970721230422e-11 ``` -------------------------------- ### Count Integrand Evaluations with QuadGK Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Use `quadgk_count` to get the integral, error estimate, and the total number of integrand evaluations. This is useful for assessing the efficiency of the integration process, particularly for functions with singularities or rapid oscillations. ```julia-repl quadgk_count(x -> exp(-x), 0, Inf) ``` -------------------------------- ### Integrate with StaticArrays.jl Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Demonstrates integrating a function returning an `SVector` from StaticArrays.jl for improved performance with small, fixed-size vectors. The result is also an `SVector`. ```julia-repl julia> using StaticArrays julia> integral, error = quadgk(x -> @SVector[1,x,x^2,x^3], 0, 1) ([1.0, 0.5, 0.3333333333333333, 0.25], 6.206335383118183e-17) julia> typeof(integral) SVector{4, Float64} (alias for SArray{Tuple{4}, Float64, 1, 4}) ``` -------------------------------- ### Batch Integrand and Buffer Management Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md Utilities for handling vectorized integrands and managing internal buffers for performance optimization. `BatchIntegrand` allows for simultaneous evaluation at multiple points. ```APIDOC ## `QuadGK.BatchIntegrand` ### Description A wrapper for vectorized integrands that can evaluate the integrand at multiple points simultaneously. ### Method `BatchIntegrand(integrand, input_buffer, output_buffer)` ## `QuadGK.quadgk_segbuf` ### Description Returns the internal segment buffer from an integration, allowing it to be reused. ### Method `quadgk_segbuf(f, a, b; kwargs...)` ## `QuadGK.quadgk_segbuf_count` ### Description Computes numerical integrals, returns the integrand evaluation count, and the segment buffer. ### Method `quadgk_segbuf_count(f, a, b; kwargs...)` ## `QuadGK.quadgk_segbuf_print` ### Description Computes numerical integrals, prints integrand evaluations, and returns the segment buffer. ### Method `quadgk_segbuf_print(f, a, b; kwargs...)` ## `QuadGK.quadgk_segbuf!` ### Description Implements an in-place API for array-valued functions, returning the segment buffer. ### Method `quadgk_segbuf!(f, a, b; kwargs...)` ## `QuadGK.alloc_segbuf` ### Description Pre-allocates a segment buffer, useful when the numeric types for domain endpoints, integral, and error estimate are known. ### Method `alloc_segbuf(T_domain, T_integral, T_error)` ``` -------------------------------- ### Integration with Integrable Singularity Source: https://context7.com/juliamath/quadgk.jl/llms.txt Demonstrates integration of a function with an integrable singularity at an endpoint. Requires careful handling and may result in a high number of evaluations. ```julia # Integrable singularity: many evaluations needed I, E, n = quadgk_count(x -> 1/sqrt(x), 0, 1) # I ≈ 2.0, n = 1305 ``` -------------------------------- ### `quadgk!` — In-place integration for array-valued integrands Source: https://context7.com/juliamath/quadgk.jl/llms.txt An in-place version of `quadgk` for integrating array-valued functions, writing the result into a pre-allocated array for memory efficiency. ```APIDOC ## `quadgk!` — In-place integration for array-valued integrands ### Description Like `quadgk`, but writes the result into a pre-allocated `result` array and accepts an in-place integrand `f!(y, x)` that writes `f(x)` into `y`. More memory-efficient for large or runtime-length array-valued integrands. Returns `(I, E)` where `I === result`. ### Method `quadgk!(f!, result, a, b...; segbuf=..., rtol=..., atol=..., order=..., norm=...) ### Parameters - `f!`: The in-place function to integrate. It takes two arguments: `y` (the output array) and `x` (the input value). - `result`: A pre-allocated array to store the integration result. - `a, b, ...`: The endpoints of the integration interval(s). - `segbuf` (optional): A pre-allocated buffer for segments, improving efficiency. - `rtol` (optional): Relative tolerance for the integration. - `atol` (optional): Absolute tolerance for the integration. - `order` (optional): The order of the quadrature rule. - `norm` (optional): A custom norm function for vector-valued integrands. ### Request Example ```julia using QuadGK # Integrate a 3-element vector-valued function in-place result = zeros(3) f!(y, x) = (y .= [sin(x), cos(x), x^2]) I, E = quadgk!(f!, result, 0.0, π) # With a pre-allocated segment buffer to avoid repeated allocation segbuf = alloc_segbuf(Float64, Vector{Float64}, Float64; size=50) I, E = quadgk!(f!, result, 0.0, π, segbuf=segbuf) # Reuse segbuf on subsequent calls with the same domain type I2, E2 = quadgk!(f!, result, 0.0, 2π, segbuf=segbuf) ``` ### Response #### Success Response (Tuple) - `I`: The estimated integral value (same as the `result` array). - `E`: An estimated upper bound on the absolute error. #### Response Example ```julia # result ≈ [2.0, 0.0, 3.289868], I === result (true) ``` ``` -------------------------------- ### Construct Weighted Gauss and Kronrod Rules Numerically Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md When only the weight function $W(x)$ and the interval $(a,b)$ are known, construct Gauss and Gauss–Kronrod rules numerically. This method requires the weight function, an integer for the number of points, and the interval endpoints. ```julia QuadGK.gauss(::Any, ::Integer, ::Real, ::Real) ``` ```julia QuadGK.kronrod(::Any, ::Integer, ::Real, ::Real) ``` -------------------------------- ### Default quadgk vs. Gauss-Jacobi (5-point) Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Compares the accuracy of the default `quadgk` function with a 5-point Gauss-Jacobi rule for integrating cos(2x) with specific weights. The default `quadgk` requires many evaluations for high accuracy, while Gauss-Jacobi provides reasonable accuracy with fewer points. ```julia-repl julia> exact = 0.9016684424525615; julia> I, _ = quadgk_count(x -> (1-x)^α * (1+x)^β * cos(2x), -1, 1, rtol=1e-9) (0.9016684425015659, 6.535590698106445e-10, 1125) julia> I - exact 4.900435612853471e-11 ``` ```julia-repl julia> I = sum(@. cos(2x) * w) 0.9016690323443182 julia> I - exact 5.898917566637962e-7 ``` -------------------------------- ### Integrate function with singularity in interior (with endpoint) Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Specifying the singularity location as an additional endpoint allows QuadGK to correctly compute the integral. ```julia-repl julia> quadgk_count(x -> 1/sqrt(abs(x-1)), 0, 1, 2) (3.9999999643041515, 5.8392038954259235e-8, 2580) ``` -------------------------------- ### Naive QuadGK on Conditionally Convergent Integral Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Demonstrates the incorrect result obtained when applying QuadGK naively to a conditionally convergent integral like the Dirichlet integral. The large error estimate highlights the issue. ```julia-repl julia> quadgk_count(x -> sin(x)/x, 0, Inf) (2.7708907564270895, 4.244645440962897, 1965) ``` -------------------------------- ### Integrate Gaussian Function from -Infinity to Infinity Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Computes the Gaussian integral from -infinity to infinity. This demonstrates `quadgk`'s ability to handle integrals over the entire real line. ```julia-repl julia> quadgk(x -> exp(-x^2), -Inf, Inf) (1.7724538509055137, 6.4296367126505234e-9) ``` -------------------------------- ### Reproducing Mathematica Result for Cauchy Principal Value Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Demonstrates the usage of the `cauchy_quadgk` function to numerically compute a Cauchy principal value integral and verifies its accuracy against a known result from Mathematica. ```julia-repl julia> cauchy_quadgk(x -> cos(x^2-1), -1, 2) (0.21245130994298977, 1.8366794196644776e-11, 60) ``` -------------------------------- ### `quadgk` — Adaptive numerical integration Source: https://context7.com/juliamath/quadgk.jl/llms.txt The primary entry point for adaptive numerical integration. It integrates a function `f(x)` over specified intervals and returns the estimated integral and error bound. ```APIDOC ## `quadgk` — Adaptive numerical integration ### Description Integrates `f(x)` over one or more contiguous intervals defined by the endpoints `a, b, c, ...`. Returns a tuple `(I, E)` where `I` is the estimated integral and `E` is an estimated upper bound on the absolute error. Tolerances `rtol` and `atol`, integration `order`, and a custom `norm` can all be specified. Endpoints may be real, infinite (`±Inf`), or complex (for contour integration). ### Method `quadgk(f, a, b...; rtol=..., atol=..., order=..., norm=...)` ### Parameters - `f`: The function to integrate. Can be a scalar, vector-valued, or complex-valued function. - `a, b, ...`: The endpoints of the integration interval(s). Can be real, `Inf`, `-Inf`, or complex. - `rtol` (optional): Relative tolerance for the integration. - `atol` (optional): Absolute tolerance for the integration. - `order` (optional): The order of the quadrature rule. - `norm` (optional): A custom norm function for vector-valued integrands. ### Request Example ```julia using QuadGK # Basic scalar integral: ∫₀¹ exp(-x²) dx integral, err = quadgk(x -> exp(-x^2), 0, 1, rtol=1e-8) # Improper integral over [0, ∞) I, E = quadgk(x -> exp(-x), 0, Inf) # Doubly-infinite integral: Gaussian integral = √π I, E = quadgk(x -> exp(-x^2), -Inf, Inf) # Subdivide at a known discontinuity at x=0.7 I, E = quadgk(x -> x < 0.7 ? sin(x) : cos(x), 0, 0.7, 1) # Vector-valued integrand: ∫₀¹ [1, x, x², x³] dx = [1, 1/2, 1/3, 1/4] I, E = quadgk(x -> [1, x, x^2, x^3], 0, 1) # Custom norm (maximum norm instead of L2) I, E = quadgk(x -> [1, x, x^2, x^3], 0, 1, norm = v -> maximum(abs, v)) # Contour integral along a diamond in the complex plane: result ≈ 2πi I, E = quadgk(z -> cos(z)/z, 1, im, -1, -im, 1) # Arbitrary-precision BigFloat integration to 50 digits setprecision(60, base=10) I, E, n = quadgk_count(x -> exp(-x^2), big"0.0", big"1.0", rtol=1e-50, order=21) ``` ### Response #### Success Response (Tuple) - `I`: The estimated integral value. - `E`: An estimated upper bound on the absolute error. #### Response Example ```julia # For basic scalar integral: # integral ≈ 0.746824132812427, err ≈ 7.9e-13 # For vector-valued integrand: # I ≈ [1.0, 0.5, 0.3333, 0.25] # For contour integral: # I ≈ 0.0 + 6.2831853im ``` ``` -------------------------------- ### Gauss and Gauss–Kronrod Rule Construction Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md Functions for constructing custom Gauss and Gauss–Kronrod quadrature rules. These are useful for specialized applications or when dealing with weighted integrals. ```APIDOC ## `QuadGK.gauss` (Unweighted) ### Description Computes Gauss quadrature rules for unweighted integrals of the form $\int_{-1}^{+1} f(x) dx$. ### Method `gauss(::Type{<:AbstractFloat}, ::Integer)` ## `QuadGK.kronrod` (Unweighted) ### Description Computes Gauss–Kronrod quadrature rules for unweighted integrals of the form $\int_{-1}^{+1} f(x) dx$. ### Method `kronrod(::Type{<:AbstractFloat}, ::Integer)` ## `QuadGK.gauss` (Weighted - Jacobi Matrix) ### Description Computes Gauss quadrature rules for weighted integrals $\int_a^b W(x) f(x) dx$ when the Jacobi matrix for the orthogonal polynomials is known. ### Method `gauss(::AbstractMatrix{<:Real}, ::Real)` ## `QuadGK.kronrod` (Weighted - Jacobi Matrix) ### Description Computes Gauss–Kronrod quadrature rules for weighted integrals $\int_a^b W(x) f(x) dx$ when the Jacobi matrix for the orthogonal polynomials is known. ### Method `kronrod(::AbstractMatrix{<:Real}, ::Integer, ::Real)` ## `QuadGK.HollowSymTridiagonal` ### Description Represents a hollow symmetric tridiagonal matrix, often used in the context of Jacobi matrices for orthogonal polynomials. ### Method `HollowSymTridiagonal(...)` ## `QuadGK.gauss` (Weighted - Numerical) ### Description Computes Gauss quadrature rules for weighted integrals $\int_a^b W(x) f(x) dx$ numerically, given only the weight function and interval. ### Method `gauss(::Any, ::Integer, ::Real, ::Real)` ## `QuadGK.kronrod` (Weighted - Numerical) ### Description Computes Gauss–Kronrod quadrature rules for weighted integrals $\int_a^b W(x) f(x) dx$ numerically, given only the weight function and interval. ### Method `kronrod(::Any, ::Integer, ::Real, ::Real)` ``` -------------------------------- ### Integrate function with singularity at endpoint Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Demonstrates integrating a function with an integrable singularity at an endpoint. Note the high number of evaluations due to the singularity. ```julia-repl julia> quadgk_count(x -> 1/sqrt(x), 0, 1) (1.9999999845983916, 2.3762511924588765e-8, 1305) ``` -------------------------------- ### Handling Singularity by Endpoint Adjustment Source: https://context7.com/juliamath/quadgk.jl/llms.txt Shows how adjusting an endpoint to coincide with a singularity can sometimes improve integration results, though it may still require many evaluations. ```julia # Helping quadgk by placing endpoint at singularity I, E, n = quadgk_count(x -> 1/sqrt(abs(x-1)), 0, 1, 2) # I ≈ 4.0, n = 2580 (much better than hitting NaN without the midpoint) ``` -------------------------------- ### Arbitrary-Precision Integration with QuadGK Source: https://context7.com/juliamath/quadgk.jl/llms.txt Performs integration using `BigFloat` for arbitrary precision. Requires setting the precision and specifies the number of evaluations. ```julia # Arbitrary-precision BigFloat integration to 50 digits setprecision(60, base=10) I, E, n = quadgk_count(x -> exp(-x^2), big"0.0", big"1.0", rtol=1e-50, order=21) # I ≈ 0.7468241328124270..., n = 129 evaluations ``` -------------------------------- ### Basic Scalar Integral with QuadGK Source: https://context7.com/juliamath/quadgk.jl/llms.txt Integrates a scalar function over a finite interval with specified relative tolerance. Returns the estimated integral and an upper bound on the absolute error. ```julia using QuadGK # Basic scalar integral: ∫₀¹ exp(-x²) dx integral, err = quadgk(x -> exp(-x^2), 0, 1, rtol=1e-8) # integral ≈ 0.746824132812427, err ≈ 7.9e-13 ``` -------------------------------- ### Compute Numerical Integrals with QuadGK Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/api.md Use `quadgk` for standard numerical integration. It supports adaptive Gauss-Kronrod quadrature for accurate results. ```julia QuadGK.quadgk ``` -------------------------------- ### `quadgk_print` — Integration with printed evaluation trace Source: https://context7.com/juliamath/quadgk.jl/llms.txt Identical to `quadgk_count` but also prints each integrand evaluation to `io` (defaults to `stdout`), useful for pedagogy and debugging. ```APIDOC ## `quadgk_print` — Integration with printed evaluation trace ### Description Identical to `quadgk_count` but also prints each integrand evaluation `f(x) = y` to `io` (defaults to `stdout`). Returns `(I, E, count)`. Primarily useful for pedagogy and debugging. ### Method `quadgk_print(io, f, a, b...; rtol=..., atol=..., order=..., norm=...) ### Parameters - `io`: The output stream to print evaluations to (defaults to `stdout`). - `f`: The function to integrate. - `a, b, ...`: The endpoints of the integration interval(s). - `rtol` (optional): Relative tolerance for the integration. - `atol` (optional): Absolute tolerance for the integration. - `order` (optional): The order of the quadrature rule. - `norm` (optional): A custom norm function for vector-valued integrands. ### Request Example ```julia using QuadGK # Example usage (output will be printed to stdout) I, E, n = quadgk_print(x -> exp(-x^2), 0, 1) ``` ### Response #### Success Response (Tuple) - `I`: The estimated integral value. - `E`: An estimated upper bound on the absolute error. - `count`: The number of times the integrand was evaluated. #### Response Example ```julia # Output to stdout might look like: # f(0.5) = 0.8775825618903728 # f(0.75) = 0.6376281516009593 # ... and so on for each evaluation. # Finally, the function returns: # I ≈ 0.746824132812427, E ≈ 7.9e-13, n = ``` ``` -------------------------------- ### Construct Kronrod Quadrature Rule Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Constructs the points and weights for a (2n+1)-point Kronrod quadrature rule. Requires a Jacobi matrix Jm where m is sufficiently large, and the integral of the weight function. It also returns embedded Gauss weights. ```julia x, w, wg = kronrod(Jₘ, n, unitintegral) ``` -------------------------------- ### Integrate Nearly Singular Function (Slow Method) Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md This function integrates a nearly singular integrand using a direct approach. It includes an explicit endpoint at x=0 if the integration domain spans it, to help QuadGK handle the singularity. Use this for comparison or when analytical subtraction is not feasible. ```julia using QuadGK function int_slow(g, α, a, b; kws...) if a < 0 < b # put an explicit endpoint at x=0 since we know it is badly behaved there return quadgk_count(x -> g(x) / (x - im*α), a, 0, b; kws...) else return quadgk_count(x -> g(x) / (x - im*α), a, b; kws...) end end ``` -------------------------------- ### In-place Vector-Valued Integration with QuadGK! Source: https://context7.com/juliamath/quadgk.jl/llms.txt Integrates a vector-valued function in-place, writing the result into a pre-allocated array. This is more memory-efficient for large or dynamically sized integrands. ```julia using QuadGK # Integrate a 3-element vector-valued function in-place result = zeros(3) f!(y, x) = (y .= [sin(x), cos(x), x^2]) I, E = quadgk!(f!, result, 0.0, π) # result ≈ [2.0, 0.0, 3.289868], I === result (true) ``` -------------------------------- ### Compare QuadGK Gauss-Jacobi with FastGaussQuadrature Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Verifies that the Gauss–Jacobi points and weights computed using QuadGK's `gauss` function with a Jacobi matrix are equivalent to those from FastGaussQuadrature's `gaussjacobi` function. ```julia-repl julia> xf, wf = FastGaussQuadrature.gaussjacobi(n, α, β); [xf wf] 5×2 Matrix{Float64}: -0.923234 0.372265 -0.589357 0.610968 -0.0806012 0.574759 0.452539 0.349891 0.852191 0.10414 julia> [x w] - [xf wf] # they are same points/weights to nearly machine precision 5×2 Matrix{Float64}: 0.0 3.33067e-16 0.0 0.0 -1.38778e-17 -2.22045e-16 5.55112e-17 -2.77556e-16 -1.11022e-16 9.71445e-17 ``` -------------------------------- ### Approximate Integral using Gauss–Legendre Rule Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/gauss-kronrod.md After obtaining the quadrature points and weights, approximate an integral by summing the product of weights and the integrand evaluated at the points. This demonstrates the accuracy of Gaussian quadrature for smooth functions. ```julia-repl julia> sum(w .* cos.(x)) # evaluate ∑ᵢ wᵢ f(xᵢ) -0.7003509770773674 julia> sin(3) - sin(1) # the exact integral -0.7003509767480293 ``` -------------------------------- ### Gauss–Kronrod Rule Points and Weights Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/gauss-kronrod.md Retrieves the points and weights for the Gauss–Kronrod rule for integration over \([-1, 1]\). The output includes points $x_i \le 0$ and their corresponding weights. ```julia-repl julia> x, w, wg = kronrod(5); [x w] # points xᵢ ≤ 0 and weights 6×2 Matrix{Float64}: -0.984085 0.042582 -0.90618 0.115233 -0.754167 0.186801 -0.538469 0.24104 -0.27963 0.27285 0.0 0.282987 ``` -------------------------------- ### Gauss-Kronrod (12-point) vs. Exact Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Shows the result of a 12-point Gauss-Kronrod rule, achieving machine precision for the integral of cos(2x). This method provides an error estimate for added confidence. ```julia-repl julia> Ik = sum(@. cos(2kx) * kw) 0.9016684424525613 julia> Ik - exact -2.220446049250313e-16 ``` -------------------------------- ### Rescale Gauss Quadrature Rule Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Rescales a Legendre W(x)=1 quadrature rule from the interval (-1,1) to a new interval (4,7) using the `gauss` function. This demonstrates how to apply custom weights and interval transformations. ```julia-repl julia> x, w = gauss(JholloW(5), 3, (-1,1) => (4,7)); [x w] 5×2 Matrix{Float64}: 4.14073 0.35539 4.6923 0.717943 5.5 0.853333 6.3077 0.717943 6.85927 0.35539 ``` -------------------------------- ### Batched Integrand Evaluation with Multi-threading Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Performs multi-threaded integration using a batched integrand function `f!(y, x)`. This is suitable for highly oscillatory functions or when integrand evaluation is computationally expensive. ```julia-repl julia> f(x) = sin(100x) f (generic function with 1 method) julia> function f!(y, x) n = Threads.nthreads() Threads.@threads for i in 1:n y[i:n:end] .= f.(@view(x[i:n:end])) end end f! (generic function with 1 method) julia> quadgk(BatchIntegrand{Float64}(f!), 0, 1) (0.0013768112771231598, 8.493080824940099e-12) ``` -------------------------------- ### Arbitrary-Precision Integration with QuadGK Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Compute integrals to arbitrary accuracy using BigFloat. Adjust the `order` parameter to improve performance for smooth integrands. ```julia-repl julia> setprecision(60, base=10) # use 60-digit arithmetic 60 julia> quadgk_count(x -> exp(-x^2), big"0.0", big"1.0", rtol=1e-50) (0.74682413281242702539946743613185300535449968681260632902766195, 6.8956257635323481758755998484087241330474674891762053644928492e-51, 15345) ``` ```julia-repl julia> quadgk_count(x -> exp(-x^2), big"0.0", big"1.0", rtol=1e-50, order=21) (0.74682413281242702539946743613185300535449968681260632902765324, 2.1873898701681913100611385149037136705674736373054902472850425e-58, 129) ``` -------------------------------- ### Integrate function with singularity in interior (without endpoint) Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Attempting to integrate a function with a singularity in the interior of the domain without specifying it as an endpoint results in an error. ```julia-repl julia> quadgk_count(x -> 1/sqrt(abs(x-1)), 0, 2) ERROR: DomainError with 1.0: integrand produced NaN in the interval (0, 2) ... ``` -------------------------------- ### Compute Gauss Quadrature Points and Weights Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Computes the Gauss quadrature points and weights for a given Jacobi matrix and unit integral. The result is a 2-column matrix with points in the first column and weights in the second. ```julia-repl julia> x, w = gauss(J(5), 2); [x w] 5×2 Matrix{Float64}: -0.90618 0.236927 -0.538469 0.478629 0.0 0.568889 0.538469 0.478629 0.90618 0.236927 ``` -------------------------------- ### Segment buffer management with quadgk_segbuf Source: https://context7.com/juliamath/quadgk.jl/llms.txt Utilize `quadgk_segbuf` to capture and reuse segment buffers across multiple integration calls. This avoids re-allocation and can be used to reuse quadrature points for derivative calculations. `alloc_segbuf` pre-allocates a buffer when domain and range types are known. ```julia using QuadGK f = x -> exp(-x^2) # First call captures the segment buffer I, E, segbuf = quadgk_segbuf(f, 0.0, 1.0, rtol=1e-8) # Reuse segbuf on subsequent calls with the same domain (avoids allocation) I2, E2 = quadgk(f, 0.0, 1.0, segbuf=segbuf) # Force re-use of exact same quadrature nodes (e.g. for finite-difference derivatives) g = x -> 2x * exp(-x^2) # f'(x) I_deriv, _ = quadgk(g, 0.0, 1.0, eval_segbuf=segbuf, maxevals=0) # Pre-allocate with known types segbuf2 = alloc_segbuf(Float64, Float64, Float64; size=100) I3, E3 = quadgk(f, 0.0, 1.0, segbuf=segbuf2) ``` -------------------------------- ### Calculate Integral and Error Estimate Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/gauss-kronrod.md Evaluate an integrand at Gauss–Kronrod points, compute the integral using the main rule's weights, and estimate the error by comparing with the embedded rule's result. This demonstrates the self-estimating nature of the method. ```julia-repl julia> fx = cos.(x); # evaluate f(xᵢ) julia> integral = sum(w .* fx) # ∑ᵢ wᵢ f(xᵢ) -0.7003509767480292 julia> error = abs(integral - sum(wg .* fx[2:2:end])) # |integral - ∑ⱼ wⱼ′ f(xⱼ′)| 3.2933822335934337e-10 ``` ```julia-repl julia> abs(integral - (sin(3) - sin(1))) # true error ≈ machine precision 1.1102230246251565e-16 ``` -------------------------------- ### QuadGK for Absolutely Convergent Laplace Transform Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Shows how QuadGK can accurately compute an absolutely convergent integral, which is a transformed version of a conditionally convergent integral. This is a step towards handling conditionally convergent integrals. ```julia-repl julia> quadgk_count(x -> exp(-1*x) * sin(x)/x, 0, Inf) (0.7853981633970302, 9.251635817418056e-10, 135) ``` ```julia-repl julia> pi/2 - atan(1) # analytical answer 0.7853981633974483 ``` -------------------------------- ### Integral with Discontinuity using QuadGK Source: https://context7.com/juliamath/quadgk.jl/llms.txt Integrates a piecewise function with a known discontinuity. The integration domain is subdivided at the point of discontinuity to improve accuracy. ```julia # Subdivide at a known discontinuity at x=0.7 I, E = quadgk(x -> x < 0.7 ? sin(x) : cos(x), 0, 0.7, 1) ``` -------------------------------- ### BatchIntegrand Source: https://context7.com/juliamath/quadgk.jl/llms.txt A wrapper type for batched and parallelized integrand evaluation, supporting multi-threading and GPU acceleration. ```APIDOC ## `BatchIntegrand` — Batched/parallelized integrand evaluation A wrapper type that enables the integrand to be evaluated at multiple quadrature nodes simultaneously, supporting user-controlled parallelism (threads, GPU, distributed). The wrapped function must have the signature `f!(y, x)`, writing results into `y` from the vector of points `x`. The `max_batch` parameter caps the maximum number of simultaneous evaluations. ```julia using QuadGK # Multi-threaded integration using Threads.@threads f(x) = sin(100x) function f_threaded!(y, x) n = Threads.nthreads() Threads.@threads for i in 1:n y[i:n:end] .= f.(@view(x[i:n:end])) end end # BatchIntegrand{Y} syntax: specify the range element type I, E = quadgk(BatchIntegrand{Float64}(f_threaded!), 0, 1) # I ≈ 0.001376811..., parallelized across threads # Explicitly pre-allocated y and x buffers for reuse y_buf = Float64[] x_buf = Float64[] bi = BatchIntegrand(f_threaded!, y_buf, x_buf; max_batch=120) I, E = quadgk(bi, 0.0, 1.0) # Cap batch size to bound memory usage bi_small = BatchIntegrand{Float64}(f_threaded!; max_batch=30) I, E = quadgk(bi_small, 0.0, 1.0) ``` ``` -------------------------------- ### Integrate Exponential Function from 0 to Infinity Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/quadgk-examples.md Computes the integral of exp(-x) from 0 to infinity. The error estimate is often pessimistic. ```julia-repl julia> quadgk(x -> exp(-x), 0, Inf) (1.0, 4.507383379289404e-11) ``` -------------------------------- ### Construct Gauss Quadrature Rule Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Constructs the points and weights for an n-point Gaussian quadrature rule given a Jacobi matrix and the integral of the weight function. The Jacobi matrix is represented by a LinearAlgebra.SymTridiagonal object. ```julia x, w = gauss(Jₙ, unitintegral) ``` -------------------------------- ### Compute Gauss Quadrature with Hollow Matrix Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Computes Gauss quadrature points and weights using a `HollowSymTridiagonal` matrix. The `gauss` function still returns all points, but computation is more efficient. ```julia-repl julia> x, w = gauss(JholloW(5), 2); [x w] 5×2 Matrix{Float64}: -0.90618 0.236927 -0.538469 0.478629 0.0 0.568889 0.538469 0.478629 0.90618 0.236927 ``` -------------------------------- ### Construct Jacobi Matrix J(n) Source: https://github.com/juliamath/quadgk.jl/blob/master/docs/src/weighted-gauss.md Constructs the n x n Jacobi matrix for Legendre polynomials. Requires the `LinearAlgebra` package. ```julia-repl julia> using LinearAlgebra # for SymTridiagonal julia> J(n) = SymTridiagonal(zeros(n), [sqrt(k^2/(4k^2-1)) for k=1:n-1]) # the n×n matrix Jₙ J (generic function with 1 method) julia> J(5) 5×5 SymTridiagonal{Float64, Vector{Float64}}: 0.0 0.57735 ⋅ ⋅ ⋅ 0.57735 0.0 0.516398 ⋅ ⋅ ⋅ 0.516398 0.0 0.507093 ⋅ ⋅ ⋅ 0.507093 0.0 0.503953 ⋅ ⋅ ⋅ 0.503953 0.0 ``` -------------------------------- ### Batched/parallelized integrand evaluation with BatchIntegrand Source: https://context7.com/juliamath/quadgk.jl/llms.txt Use `BatchIntegrand` to evaluate the integrand at multiple quadrature nodes simultaneously, enabling user-controlled parallelism. The wrapped function must have the signature `f!(y, x)`, writing results into `y` from the vector of points `x`. `max_batch` caps the number of simultaneous evaluations. ```julia using QuadGK # Multi-threaded integration using Threads.@threads f(x) = sin(100x) function f_threaded!(y, x) n = Threads.nthreads() Threads.@threads for i in 1:n y[i:n:end] .= f.(@view(x[i:n:end])) end end # BatchIntegrand{Y} syntax: specify the range element type I, E = quadgk(BatchIntegrand{Float64}(f_threaded!), 0, 1) # Explicitly pre-allocated y and x buffers for reuse y_buf = Float64[] x_buf = Float64[] bi = BatchIntegrand(f_threaded!, y_buf, x_buf; max_batch=120) I, E = quadgk(bi, 0.0, 1.0) # Cap batch size to bound memory usage bi_small = BatchIntegrand{Float64}(f_threaded!; max_batch=30) I, E = quadgk(bi_small, 0.0, 1.0) ``` -------------------------------- ### quadgk_segbuf / alloc_segbuf Source: https://context7.com/juliamath/quadgk.jl/llms.txt Manages segment buffers for efficient reuse of quadrature results and allocations across multiple integration calls. ```APIDOC ## `quadgk_segbuf` / `alloc_segbuf` — Segment buffer management `quadgk_segbuf` is like `quadgk` but returns a triple `(I, E, segbuf)` where `segbuf` captures the final subdivision of the domain. This buffer can be passed back to subsequent `quadgk` calls via `segbuf=` (to avoid re-allocation) or `eval_segbuf=` (to reuse the same quadrature points, e.g. for computing derivatives). `alloc_segbuf` pre-allocates a buffer when the domain and range types are known in advance. ```julia using QuadGK f = x -> exp(-x^2) # First call captures the segment buffer I, E, segbuf = quadgk_segbuf(f, 0.0, 1.0, rtol=1e-8) # Reuse segbuf on subsequent calls with the same domain (avoids allocation) I2, E2 = quadgk(f, 0.0, 1.0, segbuf=segbuf) # Force re-use of exact same quadrature nodes (e.g. for finite-difference derivatives) g = x -> 2x * exp(-x^2) # f'(x) I_deriv, _ = quadgk(g, 0.0, 1.0, eval_segbuf=segbuf, maxevals=0) # Pre-allocate with known types segbuf2 = alloc_segbuf(Float64, Float64, Float64; size=100) I3, E3 = quadgk(f, 0.0, 1.0, segbuf=segbuf2) ``` ```