Skip to content

fun #

Special Functions (fun) Module

The vsl.fun module provides a comprehensive collection of special mathematical functions commonly used in scientific computing, engineering, and mathematical analysis.

🚀 Features

Bessel Functions

  • Cylindrical J, Y, I, and K functions support integer orders, including common order-zero and order-one variants.
  • Spherical j_n and y_n functions support non-negative integer orders.
  • Fractional-order cylindrical functions remain tracked in issue #541.

Airy Functions

  • airy(x) returns AiryValues{ai, bi, aip, bip, err}: Ai, Bi and their first derivatives, with err bounding the absolute error of the four values.
  • airy_scaled(x) returns the SciPy airye forms: for x >= 0, Ai and Ai' times exp(zeta) and Bi and Bi' times exp(-zeta), with zeta = 2/3 x^(3/2). For x < 0 nothing is scaled.
  • Convenience functions airy_ai, airy_bi, airy_aip and airy_bip return single values.
  • Method: double-double Maclaurin series on |x| <= 8; oscillatory asymptotic expansion for x < -8 (relative error about 1e-14 at x = -8); decaying asymptotic expansion for x > 8 (relative error about 1e-13 at x = 8). Measured against 140-digit references, the series region is held to 1e-13 relative error and the asymptotic regions to 1e-12.
  • Special values: NaN propagates; Ai(+inf) = Ai'(+inf) = 0, Bi(+inf) = Bi'(+inf) = +inf; every value is NaN at -inf. Unscaled Bi and Bi' overflow to +inf beyond x of about 104.
  • Accuracy for x < -1e6 degrades roughly with zeta * 2.2e-16, because the phase of the oscillation is rounded in double precision; err includes this term.

Gamma Functions

  • Gamma Function: Γ(x) and related functions
  • Log Gamma: Numerically stable logarithmic form
  • Complex Gamma: Support for complex arguments
  • Digamma Function: Ψ(x) - logarithmic derivative of gamma

Error Functions

  • Error Function: erf(x) and complementary erfc(x)
  • Inverse error functions erf_inv(x) and erfc_inv(x) handle finite domains, endpoints, and tails.
  • The scaled complementary error function erfcx(x) uses a positive-tail expansion to avoid overflow and underflow. It returns zero at positive infinity and may overflow for sufficiently negative finite inputs.

Interpolation

  • Cubic Interpolation: Smooth curve fitting
  • Quadratic Interpolation: Efficient polynomial fitting
  • Data Interpolation: General-purpose data fitting

Trigonometric and Sinusoid Functions

  • Sine and cosine functions with error estimates.
  • Parameterized sinusoid helpers for fitting and Fourier approximations.

📖 Usage Examples

Bessel Function Example

import vsl.fun

// Standard Bessel function of the first kind
x := 2.5
order := 1
result := fun.bessel_jn(order, x)
println('J_1(2.5) = ${result}')

// Modified Bessel function
result_i := fun.bessel_in(order, x)
println('I_1(2.5) = ${result_i}')

// Spherical Bessel functions use non-negative integer orders.
spherical_j := fun.spherical_bessel_jn(2, x)
spherical_y := fun.spherical_bessel_yn(2, x)
println('j_2(2.5) = ${spherical_j}; y_2(2.5) = ${spherical_y}')

Gamma Function Example

import vsl.fun

// Standard gamma function
x := 3.5
gamma_val := fun.gamma(x)
println('Γ(3.5) = ${gamma_val}')

// Log gamma for large arguments (numerically stable)
log_gamma_val := fun.log_gamma(x)
println('ln(Γ(3.5)) = ${log_gamma_val}')

Error Function Example

import vsl.fun

// Error function - common in statistics
x := 1.0
erf_val := fun.erf(x)
println('erf(1.0) = ${erf_val}')

// Complementary error function
erfc_val := fun.erfc(x)
println('erfc(1.0) = ${erfc_val}')

// Invert the error functions for a Gaussian-tail calculation
quantile := fun.erf_inv(0.95)
tail := fun.erfc_inv(1e-12)
scaled_tail := fun.erfcx(10.0)
println('erf inverse = ${quantile}, erfc tail inverse = ${tail}')
println('scaled complementary tail = ${scaled_tail}')

Interpolation Example

import vsl.fun

// Data points for interpolation
x_data := [0.0, 1.0, 2.0, 3.0]
y_data := [1.0, 4.0, 9.0, 16.0]

// Create cubic interpolator
mut interp := fun.InterpCubic.new()
interp.fit_4points(x_data[0], y_data[0], x_data[1], y_data[1], x_data[2], y_data[2], x_data[3],
    y_data[3])!

// Evaluate at intermediate point
x_new := 1.5
y_new := interp.f(x_new)
println('Interpolated value at x=1.5: ${y_new}')

🔬 Mathematical Background

Bessel Function Background

Bessel functions arise in solving Laplace's equation in cylindrical coordinates. They appear in:

  • Wave propagation problems
  • Heat conduction in cylinders
  • Quantum mechanics (radial wave functions)
  • Electromagnetic field problems

Gamma Function Background

The gamma function extends the factorial to real and complex numbers:

  • Γ(n) = (n-1)! for positive integers
  • Used in probability distributions
  • Appears in many integrals and series

Error Function Background

Related to the Gaussian distribution:

  • erf(x) = (2/√π) ∫₀ˣ e^(-t²) dt
  • Fundamental in statistics and probability
  • Used in diffusion processes

🎯 Examples

See these examples for practical applications:

  • prime_factorization - Uses gamma function properties
  • data_analysis_example - Statistical functions
  • noise_* examples - Error functions in random processes

🔧 Performance Notes

  • Table-based functions: Some functions use precomputed tables for speed
  • Asymptotic expansions: Used for large arguments
  • Continued fractions: Employed for intermediate ranges
  • Error handling: Graceful handling of domain errors

🐛 Current Limitations

  • Cylindrical Bessel functions currently support integer orders. Spherical j_n and y_n are available for non-negative integer orders; fractional-order cylindrical families are tracked in issue #541.
  • Bessel functions do not expose error estimates; see issue #543.
  • Extended-precision variants are not available.

📚 API Reference

Core Functions

Bessel Functions:

  • bessel_jn(n, x) - Bessel function of the first kind
  • bessel_yn(n, x) - Bessel function of the second kind
  • bessel_in(n, x) - Modified Bessel function of the first kind
  • bessel_kn(n, x) - Modified Bessel function of the second kind

Gamma Functions:

  • gamma(x) - Gamma function
  • log_gamma(x) - Logarithm of gamma function
  • digamma(x) - Digamma function (ψ function)

Error Functions:

  • erf(x) - Error function
  • erfc(x) - Complementary error function
  • erf_inv(x) - Inverse error function for [-1, 1]; infinities at endpoints.
  • erfc_inv(x) - Inverse complementary error function for [0, 2]; infinities at endpoints.
  • erfcx(x) - Scaled complementary error function; positive tails remain finite for large finite inputs.

🔗 References

  • Abramowitz & Stegun: "Handbook of Mathematical Functions"
  • NIST Digital Library of Mathematical Functions
  • Numerical Recipes in Scientific Computing

For more special functions, see the VSL documentation and examples directory.

fn airy #

fn airy(x f64) AiryValues

airy computes Ai, Bi, Ai' and Bi' at x, in unscaled form.

fn airy_ai #

fn airy_ai(x f64) f64

airy_ai returns Ai(x).

fn airy_aip #

fn airy_aip(x f64) f64

airy_aip returns Ai'(x).

fn airy_bi #

fn airy_bi(x f64) f64

airy_bi returns Bi(x).

fn airy_bip #

fn airy_bip(x f64) f64

airy_bip returns Bi'(x).

fn airy_scaled #

fn airy_scaled(x f64) AiryValues

airy_scaled computes the exponentially scaled forms, as SciPy's airye does. For x >= 0, Ai and Ai' are multiplied by exp(zeta) and Bi and Bi' by exp(-zeta), with zeta = 2/3 x^{3/2}. For x < 0 the result equals airy(x).

fn atan2p #

fn atan2p(y f64, x f64) f64

atan2p implements a positive version of atan2, in such a way that: 0 ≤ α ≤ 2π

fn atan2pdeg #

fn atan2pdeg(y f64, x f64) f64

atan2pdeg implements a positive version of atan2, in such a way that: 0 ≤ α ≤ 360

fn bessel_i0 #

fn bessel_i0(x f64) f64

bessel_i0 returns the modified Bessel function i0(x) for any real x.

fn bessel_i1 #

fn bessel_i1(x f64) f64

bessel_i1 returns the modified Bessel function i1(x) for any real x.

fn bessel_in #

fn bessel_in(n int, x f64) f64

bessel_in returns the modified Bessel function in(x) for any real x and n ≥ 0

fn bessel_j0 #

fn bessel_j0(x_ f64) f64

bessel_j0 returns the order-zero Bessel function of the first kind.

special cases are: bessel_j0(±inf) = 0 bessel_j0(0) = 1 bessel_j0(nan) = nan

fn bessel_j1 #

fn bessel_j1(x_ f64) f64

bessel_j1 returns the order-one Bessel function of the first kind.

special cases are: bessel_j1(±inf) = 0 bessel_j1(nan) = nan

fn bessel_jn #

fn bessel_jn(n_ int, x_ f64) f64

bessel_jn returns the order-n Bessel function of the first kind.

special cases are: bessel_jn(n, ±inf) = 0 bessel_jn(n, nan) = nan

fn bessel_k0 #

fn bessel_k0(x f64) f64

bessel_k0 returns the modified Bessel function k0(x) for positive real x. special cases: K0(x=0) = +inf K0(x<0) = nan

fn bessel_k1 #

fn bessel_k1(x f64) f64

bessel_k1 returns the modified Bessel function k1(x) for positive real x. special cases: K0(x=0) = +inf K0(x<0) = nan

fn bessel_kn #

fn bessel_kn(n int, x f64) f64

bessel_kn returns the modified Bessel function kn(x) for positive x and n ≥ 0

fn bessel_y0 #

fn bessel_y0(x f64) f64

bessel_y0 returns the order-zero Bessel function of the second kind.

special cases are: bessel_y0(+inf) = 0 bessel_y0(0) = -inf bessel_y0(x < 0) = nan bessel_y0(nan) = nan

fn bessel_y1 #

fn bessel_y1(x f64) f64

bessel_y1 returns the order-one Bessel function of the second kind.

special cases are: bessel_y1(+inf) = 0 bessel_y1(0) = -inf bessel_y1(x < 0) = nan bessel_y1(nan) = nan

fn bessel_yn #

fn bessel_yn(n_ int, x f64) f64

bessel_yn returns the order-n Bessel function of the second kind.

special cases are: bessel_yn(n, +inf) = 0 bessel_yn(n ≥ 0, 0) = -inf bessel_yn(n < 0, 0) = +inf if n is odd, -inf if n is even bessel_yn(n, x < 0) = nan bessel_yn(n, nan) = nan

fn beta #

fn beta(a f64, b f64) f64

beta computes the beta function by calling the log_gamma_sign function

fn binomial #

fn binomial(n int, k_ int) f64

binomial comptues the binomial coefficient (n k)^t

fn boxcar #

fn boxcar(x f64, a f64, b f64) f64

boxcar implements the boxcar function

boxcar(x;a,b) = heav(x-a) - heav(x-b)

NOTE: a ≤ x ≤ b; i.e. b ≥ a (not checked)

fn cgamma #

fn cgamma(z cmplx.Complex) cmplx.Complex

gamma computes the gamma function value

fn choose #

fn choose(n int, p int) f64

Compute the binomial coefficient

fn clog_gamma #

fn clog_gamma(z cmplx.Complex) cmplx.Complex

log_gamma computes the log-gamma function value

fn cos #

fn cos(x f64) f64

cos exposes this operation as part of the public API.

fn cos_e #

fn cos_e(x f64) (f64, f64)

cos_e exposes this operation as part of the public API.

fn digamma #

@[inline]
fn digamma(x f64) f64

digamma exposes this operation as part of the public API.

fn erf #

fn erf(x_ f64) f64

erf returns the error function of x.

special cases are: erf(+inf) = 1 erf(-inf) = -1 erf(nan) = nan

fn erf_inv #

fn erf_inv(x f64) f64

erf_inv returns the inverse error function for x in [-1, 1].

It returns -infinity at -1, +infinity at 1, and NaN for NaN or values outside the domain. For finite interior inputs, the approximation is refined with Halley's method; small inputs use a series to avoid loss of significance near zero.

fn erfc #

fn erfc(x_ f64) f64

erfc returns the complementary error function of x.

special cases are: erfc(+inf) = 0 erfc(-inf) = 2 erfc(nan) = nan

fn erfc_inv #

fn erfc_inv(x f64) f64

erfc_inv returns the inverse complementary error function for x in [0, 2].

It returns +infinity at 0, -infinity at 2, zero at 1, and NaN for NaN or values outside the domain. Tail evaluation uses erfc directly so values near zero do not lose precision through 1 - erf(x).

fn erfcx #

fn erfcx(x f64) f64

erfcx returns the scaled complementary error function exp(x*x) * erfc(x).

Positive tails use an asymptotic expansion to avoid overflow in exp(x*x) and underflow in erfc(x). The function returns NaN for NaN, zero at positive infinity, and positive infinity at negative infinity or when the true value exceeds the f64 range.

fn exp_mix #

fn exp_mix(x f64) cmplx.Complex

exp_mix uses euler's formula to compute exp(-i⋅x) = cos(x) - i⋅sin(x)

fn exp_pix #

fn exp_pix(x f64) cmplx.Complex

exp_pix uses euler's formula to compute exp(+i⋅x) = cos(x) + i⋅sin(x)

fn fib #

fn fib(n int) int

fib returns the nth number in the Fibonacci sequence using O(1) space in O(logn) time complexity

fn gamma #

fn gamma(x_ f64) f64

gamma returns the gamma function of x.

special ifs are: gamma(+inf) = +inf gamma(+0) = +inf gamma(-0) = -inf gamma(x) = nan for integer x < 0 gamma(-inf) = nan gamma(nan) = nan

fn hat #

fn hat(x f64, xc f64, y0 f64, h f64, l f64) f64

hat implements the hat function

fn hatd1 #

fn hatd1(x f64, xc f64, y0 f64, h f64, l f64) f64

hatd1 returns the first derivative of the hat function NOTE: the discontinuity is ignored ⇒ d1(xc-l)=d1(xc+l)=d1(xc)=0

fn heav #

fn heav(x f64) f64

heav computes the heaviside step function (== derivative of ramp(x))

│ 0 if x < 0 heav(x) = ┤ 1/2 if x = 0 │ 1 if x > 0

fn hypot #

fn hypot(x f64, y f64) f64

hypot exposes this operation as part of the public API.

fn hypot_e #

fn hypot_e(x f64, y f64) (f64, f64)

hypot_e exposes this operation as part of the public API.

fn imag_pow_n #

fn imag_pow_n(n int) cmplx.Complex

imag_pow_n computes iⁿ = (√-1)ⁿ

fn imag_x_pow_n #

fn imag_x_pow_n(x f64, n int) cmplx.Complex

imag_x_pow_n computes (x⋅i)ⁿ

fn lin_interp #

fn lin_interp(mut o DataInterp, j int, x f64) f64

lin_interp implements linear interpolator

fn log_gamma #

fn log_gamma(x f64) f64

log_gamma returns the natural logarithm and sign (-1 or +1) of Gamma(x).

special ifs are: log_gamma(+inf) = +inf log_gamma(0) = +inf log_gamma(-integer) = +inf log_gamma(-inf) = -inf log_gamma(nan) = nan

fn log_gamma_sign #

fn log_gamma_sign(x_ f64) (f64, int)

log_gamma_sign exposes this operation as part of the public API.

fn logistic #

fn logistic(z f64) f64

logistic implements the sigmoid/logistic function

fn logistic_d1 #

fn logistic_d1(z f64) f64

logistic_d1 implements the first derivative of the sigmoid/logistic function

fn n_combos_w_replacement #

fn n_combos_w_replacement(n f64, r f64) u64

(n+r-1)! / r! / (n-1)! when n > 0.

fn neg_one_pow_n #

fn neg_one_pow_n(n int) f64

neg_one_pow_n computes (-1)ⁿ

fn poly_interp #

fn poly_interp(mut o DataInterp, jl int, x f64) f64

poly_interp performs a polynomial interpolation. this routine returns an interpolated value y, and stores an error estimate dy. the returned value is obtained by m-point polynomial interpolation on the subrange xx[jl..jl+m-1].

fn pone #

fn pone(x f64) f64

For x >= 8, the asymptotic expansions of pone is 1 + 15/128 s2 - 4725/215 s4 - ..., where s = 1/x. We approximate pone by pone(x) = 1 + (R/S) where R = pr0 + pr1*s2 + pr2s**4 + ... + pr5s10 S = 1 + ps0*s2 + ... + ps4*s10 and | pone(x)-1-R/S | <= 2(-60.06)

fn pow2 #

fn pow2(x f64) f64

pow2 computes x²

fn pow3 #

fn pow3(x f64) f64

pow3 computes x³

fn powp #

fn powp(x_ f64, n u32) f64

powp computes real raised to positive integer xⁿ

fn psi #

fn psi(x_ f64) f64

psi exposes this operation as part of the public API.

fn pzero #

fn pzero(x f64) f64

The asymptotic expansions of pzero is 1 - 9/128 s2 + 11025/98304 s4 - ..., where s = 1/x. For x >= 2, We approximate pzero by pzero(x) = 1 + (R/S) where R = pj0r0 + pR1s**2 + pR2s4 + ... + pR5*s10 S = 1 + pj0s0s**2 + ... + pS4s**10 and | pzero(x)-1-R/S | <= 2 ** ( -60.26)

fn qone #

fn qone(x f64) f64

For x >= 8, the asymptotic expansions of qone is 3/8 s - 105/1024 s3 - ..., where s = 1/x. We approximate qone by qone(x) = s*(0.375 + (R/S)) where R = qr1*s2 + qr2s**4 + ... + qr5s10 S = 1 + qs1*s2 + ... + qs6*s12 and | qone(x)/s -0.375-R/S | <= 2(-61.13)

fn qzero #

fn qzero(x f64) f64

For x >= 8, the asymptotic expansions of qzero is -1/8 s + 75/1024 s3 - ..., where s = 1/x. We approximate pzero by qzero(x) = s*(-1.25 + (R/S)) where R = qj0r0 + qR1*s2 + qR2s**4 + ... + qR5s10 S = 1 + qj0s0*s2 + ... + qS5*s12 and | qzero(x)/s +1.25-R/S | <= 2(-61.22)

fn ramp #

fn ramp(x f64) f64

ramp function => macaulay brackets

fn rbinomial #

fn rbinomial(x f64, y f64) f64

rbinomial computes the binomial coefficient with real (non-negative) arguments by calling the gamma function

fn rect #

fn rect(x f64) f64

rect implements the rectangular function

rect(x) = boxcar(x;-0.5,0.5)

fn sabs #

fn sabs(x f64, eps f64) f64

sabs implements a smooth abs f: sabs(x) = x*x / (sign(x)*x + eps)

fn sabs_d1 #

fn sabs_d1(x f64, eps f64) f64

sabs_d1 returns the first derivative of sabs

fn sabs_d2 #

fn sabs_d2(x f64, eps f64) f64

sabs_d2 returns the first derivative of sabs

fn sign #

fn sign(x f64) f64

sign implements the sign function

fn sin #

fn sin(x f64) f64

sin exposes this operation as part of the public API.

fn sin_e #

fn sin_e(x f64) (f64, f64)

sin_e exposes this operation as part of the public API.

fn sinc #

fn sinc(x f64) f64

sinc computes the sine cardinal (sinc) function

sinc(x) = | 1 if x = 0 | sin(x)/x otherwise

fn spherical_bessel_jn #

fn spherical_bessel_jn(n int, x f64) f64

spherical_bessel_jn returns the spherical Bessel function j_n(x) for non-negative integer order. Negative arguments follow j_n(-x)=(-1)^n*j_n(x). Negative orders return NaN.

fn spherical_bessel_yn #

fn spherical_bessel_yn(n int, x f64) f64

spherical_bessel_yn returns the spherical Bessel function y_n(x) for non-negative integer order and x > 0. Negative arguments and orders return NaN; the singular value at zero is negative infinity.

fn sramp #

fn sramp(x f64, beta f64) f64

sramp implements a smooth ramp function. ramp

fn srampd1 #

fn srampd1(x f64, beta f64) f64

srampd1 returns the first derivative of sramp

fn srampd2 #

fn srampd2(x f64, beta f64) f64

srampd2 returns the second derivative of sramp

fn suqcos #

fn suqcos(angle f64, expon f64) f64

suqcos implements the superquadric auxiliary function that uses cos(x)

fn suqsin #

fn suqsin(angle f64, expon f64) f64

suqsin implements the superquadric auxiliary function that uses sin(x)

fn uint_binomial #

fn uint_binomial(n_ u64, k_ u64) u64

uint_binomial implements the binomial coefficient using u64. panic happens on overflow also, this function uses a loop so it may not be very efficient for large k the code below comes from https://en.wikipedia.org/wiki/binomial_coefficient [cannot find a reference to cite]

fn DataInterp.new #

fn DataInterp.new(itype string, p int, xx []f64, yy []f64) &DataInterp

DataInterp.new creates new interpolator for data point sets xx and yy (with same lengths)

type -- type of interpolator "lin" : linear "poly" : polynomial

p -- order of interpolator xx -- x-data yy -- y-data

fn InterpCubic.new #

fn InterpCubic.new() &InterpCubic

InterpCubic.new returns a new InterpCubic instance

fn InterpQuad.new #

fn InterpQuad.new() &InterpQuad

InterpQuad.new returns a new InterpQuad instance

fn Sinusoid.basis #

fn Sinusoid.basis(t f64, a0 f64, a1 f64, b1 f64) &Sinusoid

Sinusoid.basis creates a new sinusoid object with the "basis" parameters set t -- period; e.g. [s] a0 -- mean value; e.g. [m] a1 -- coefficient of the cos term b1 -- coefficient of the sin term

fn Sinusoid.essential #

fn Sinusoid.essential(t f64, a0 f64, c1 f64, theta f64) &Sinusoid

Sinusoid.essential creates a new sinusoid object with the "essential" parameters set t -- period; e.g. [s] a0 -- mean value; e.g. [m] c1 -- amplitude; e.g. [m] theta -- phase shift; e.g. [rad]

type InterpFn #

type InterpFn = fn (mut o DataInterp, j int, x f64) f64

InterpFn defines the type of the implementation of the data interpolation

struct AiryValues #

struct AiryValues {
pub:
	ai  f64
	bi  f64
	aip f64
	bip f64
	err f64
}

AiryValues holds Ai, Bi and their first derivatives at one point. err is an estimate of the largest absolute error among the four values, derived from the method used.

struct ChebSeries #

struct ChebSeries {
pub:
	c     []f64 // coefficients
	order int   // order of expansion
	a     f64   // lower interval point
	b     f64   // upper interval point
}

data for a Chebyshev series over a given interval

fn (ChebSeries) eval_e #

fn (cs ChebSeries) eval_e(x f64) (f64, f64)

eval_e exposes this operation as part of the public API.

struct DataInterp #

@[heap]
struct DataInterp {
mut:
	// input data
	itype string // type of interpolator
	xx    []f64  // x-data values
	yy    []f64  // y-data values
	// derived data
	m        int  // number of points of interpolating formula; e.g. 2 for segments, 3 for 2nd order polynomials
	n        int  // length of xx
	j_hunt   int  // temporary j to decide on using hunt
	dj_hunt  int  // increent of j to decide on using hunt function or locate
	use_hunt bool // use hunt code instead of locate
	ascnd    bool // ascending order of x-values
	// implementation
	interp InterpFn = unsafe { nil }
pub mut:
	// configuration data
	disable_hunt bool // do not use hunt code at all
	// output data
	dy f64 // error estimate
}

DataInterp defines a public data structure for this module.

fn (DataInterp) reset #

fn (mut o DataInterp) reset(xx []f64, yy []f64)

reset re-assigns xx and yy data sets

fn (DataInterp) p #

fn (mut o DataInterp) p(x f64) f64

p computes p(x); i.e. performs the interpolation

fn (DataInterp) locate #

fn (mut o DataInterp) locate(x f64) int

locate returns a value j such that x is (insofar as possible) centered in the subrange xx[j..j+mm-1], where xx is the stored pointer. the values in xx must be monotonic, either increasing or decreasing. the returned value is not less than 0, nor greater than n-1.

fn (DataInterp) hunt #

fn (mut o DataInterp) hunt(x f64) int

hunt returns a value j such that x is (insofar as possible) centered in the subrange xx[j..j+mm-1], where xx is the stored pointer. the values in xx must be monotonic, either increasing or decreasing. the returned value is not less than 0, nor greater than n-1.

struct InterpCubic #

struct InterpCubic {
pub mut:
	// coefficients of polynomial a, b, c, d
	a f64
	b f64
	c f64
	d f64
	// tolerance to avoid zero denominator
	tol_den f64
}

InterpCubic computes a cubic polynomial to perform interpolation either using 4 points or 3 points and a known derivative

fn (InterpCubic) f #

fn (o InterpCubic) f(x f64) f64

f computes y = f(x) curve

fn (InterpCubic) g #

fn (o InterpCubic) g(x f64) f64

g computes y' = df/x|(x) curve

fn (InterpCubic) critical #

fn (o InterpCubic) critical() (f64, f64, f64, bool, bool, bool)

critical returns the critical points xmin -- x @ min and y(xmin) xmax -- x @ max and y(xmax) xifl -- x @ inflection point and y(ifl) has_min, has_max, has_ifl -- flags telling what is available

fn (InterpCubic) fit_4points #

fn (mut o InterpCubic) fit_4points(x0 f64, y0 f64, x1 f64, y1 f64, x2 f64, y2 f64, x3 f64, y3 f64) !

fit_4points fits polynomial to 3 points (x0, y0) -- first point (x1, y1) -- second point (x2, y2) -- third point (x3, y3) -- fourth point

fn (InterpCubic) fit_3points_d #

fn (mut o InterpCubic) fit_3points_d(x0 f64, y0 f64, x1 f64, y1 f64, x2 f64, y2 f64, x3 f64, d3 f64) !

fit_3points_d fits polynomial to 3 points and known derivative (x0, y0) -- first point (x1, y1) -- second point (x2, y2) -- third point (x3, d3) -- derivative @ x3

struct InterpQuad #

struct InterpQuad {
pub mut:
	// coefficients of polynomial a, b, c
	a f64
	b f64
	c f64
	// tolerance to avoid zero denominator
	tol_den f64
}

InterpQuad computes a quadratic polynomial to perform interpolation either using 3 points or 2 points and a known derivative

fn (InterpQuad) f #

fn (o InterpQuad) f(x f64) f64

f computes y = f(x) curve

fn (InterpQuad) g #

fn (o InterpQuad) g(x f64) f64

g computes y' = df/x|(x) curve

fn (InterpQuad) optimum #

fn (o InterpQuad) optimum() (f64, f64)

optimum returns the minimum or maximum point; i.e. the point with zero derivative xopt -- x @ optimum fopt -- f(xopt) = y @ optimum

fn (InterpQuad) fit_3points #

fn (mut o InterpQuad) fit_3points(x0 f64, y0 f64, x1 f64, y1 f64, x2 f64, y2 f64) !

fit_3points fits polynomial to 3 points (x0, y0) -- first point (x1, y1) -- second point (x2, y2) -- third point

fn (InterpQuad) fit_2points_d #

fn (mut o InterpQuad) fit_2points_d(x0 f64, y0 f64, x1 f64, y1 f64, x2 f64, d2 f64) !

fit_2points_d fits polynomial to 2 points and known derivative (x0, y0) -- first point (x1, y1) -- second point (x2, d2) -- derivate @ x2

struct Sinusoid #

struct Sinusoid {
pub mut:
	// input
	period      f64 // t: period; e.g. [s]
	mean_value  f64 // a0: mean value; e.g. [m]
	amplitude   f64 // c1: amplitude; e.g. [m]
	phase_shift f64 // theta: phase shift; e.g. [rad]
	// derived
	frequency    f64 // f: frequency; e.g. [Hz] or [1 cycle/s]
	angular_freq f64 // omega_0 = 2⋅π⋅f: angular frequency; e.g. [rad⋅s⁻¹]
	time_shift   f64 // ts = theta / omega_0: time shift; e.g. [s]
	// derived: coefficients
	a []f64 // a0, a1, A2, ... (if series mode)
	b []f64 // B0, b1, B2, ... (if series mode)
}

Sinusoid implements the sinusoid equation:

y(t) = a0 + c1⋅cos(omega_0⋅t + theta) [essential-form]

y(t) = a0 + a1⋅cos(omega_0⋅t) + b1⋅sin(omega_0⋅t) [basis-form]

a1 = c1⋅cos(theta) b1 = -c1⋅sin(theta) theta = arctan(-b1 / a1) if a1<0, theta += π c1 = sqrt(a1² + b1²)

fn (Sinusoid) yessen #

fn (o Sinusoid) yessen(t f64) f64

yessen computes y(t) = a0 + c1⋅cos(omega_0⋅t + theta [essential-form]

fn (Sinusoid) ybasis #

fn (o Sinusoid) ybasis(t f64) f64

ybasis computes y(t) = a0 + a1⋅cos(omega_0⋅t) + b1⋅sin(omega_0⋅t) [basis-form]

fn (Sinusoid) approx_square_fourier #

fn (mut o Sinusoid) approx_square_fourier(n int)

approx_square_fourier approximates sinusoid using Fourier series with n terms

fn (Sinusoid) test_periodicity #

fn (o Sinusoid) test_periodicity(tmin f64, tmax f64, npts int) bool

test_periodicity tests that f(t) = f(t + t)