diffalgebra

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package diffalgebra provides symbolic tools for differential algebra and linear ordinary differential equations over the rational numbers.

The package is built up from a small tower of exact algebraic types and a large collection of genuinely distinct operations on them:

  • Exact rational numbers via math/big and dense univariate polynomials Poly over Q with the full complement of ring operations: addition, multiplication, Euclidean division, greatest common divisors, extended GCD, resultants, discriminants, square-free factorisation, rational-root isolation, composition and formal differentiation and integration.

  • Rational functions RatFunc = Poly/Poly forming the differential field Q(x) with the standard derivation d/dx (Derivation), logarithmic derivatives, partial-fraction decomposition and exact arithmetic.

  • Linear differential operators Operator with rational-function coefficients, forming the non-commutative Ore ring Q(x)[D] with the relation D*a = a*D + a'. Operators can be added, composed, applied to functions, raised to powers and reduced to their formal adjoint and symbol.

  • Wronskians (WronskianPoly, WronskianRatFunc) and the induced linear-independence tests, built on exact determinants over Q(x).

  • Symbolic solution of constant-coefficient linear ODEs and recurrences (SolveLinearConstantODE, SolveLinearRecurrence) via numerically computed characteristic roots grouped into exact multiplicities, together with initial-value fitting by exact/complex linear algebra.

  • The variation-of-parameters construction (VariationOfParameters) that turns a fundamental system into the integrands of a particular solution.

  • Elementary integration of rational functions by Hermite reduction (HermiteReduce) and the Rothstein-Trager resultant method (IntegrateRational), plus the Risch structure-theorem heuristics for simple exponential integrands (RischExpIntegrate).

  • The Kovacic algorithm (Kovacic) for detecting Liouvillian solutions of second-order linear ODEs y” = r y with r in Q(x), including reduction of a general second-order equation to normal form (ReduceToNormalForm).

Everything is implemented with the Go standard library only. Symbolic data is exact over Q; numerical routines (root finding, initial-value fitting) accept a caller-supplied seed for reproducibility and never read the wall clock.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrDivByZero indicates division by a zero polynomial or rational function.
	ErrDivByZero = errors.New("diffalgebra: division by zero")
	// ErrDim indicates a shape or dimension mismatch between operands.
	ErrDim = errors.New("diffalgebra: dimension mismatch")
	// ErrNotSquare indicates that a square matrix was required.
	ErrNotSquare = errors.New("diffalgebra: matrix is not square")
	// ErrSingular indicates a singular (non-invertible) linear system.
	ErrSingular = errors.New("diffalgebra: singular linear system")
	// ErrEmpty indicates that an empty argument was supplied where at least one
	// element is required.
	ErrEmpty = errors.New("diffalgebra: empty argument")
	// ErrDegree indicates an unsupported or inconsistent polynomial degree.
	ErrDegree = errors.New("diffalgebra: unsupported degree")
	// ErrNoSolution indicates that no solution of the requested kind exists.
	ErrNoSolution = errors.New("diffalgebra: no solution")
	// ErrNonRational indicates that a residue or exponent was not rational and
	// could therefore not be expressed exactly over Q.
	ErrNonRational = errors.New("diffalgebra: non-rational value")
	// ErrConverge indicates that a numerical iteration failed to converge.
	ErrConverge = errors.New("diffalgebra: failed to converge")
)

Sentinel errors returned throughout the package.

Functions

func CharacteristicComplexRoots

func CharacteristicComplexRoots(coeffs []float64, seed int64) []complex128

CharacteristicComplexRoots returns the complex characteristic roots of the coefficient vector (coeffs[i] the coefficient of y^(i)).

func HermiteReduce

func HermiteReduce(f RatFunc) (rational RatFunc, remaining RatFunc)

HermiteReduce performs Hermite reduction of the rational function f, returning the elementary rational part of its integral together with a remaining integrand whose denominator is square-free (so that its integral is a sum of logarithms). It always succeeds.

func KovacicSolveSecondOrder

func KovacicSolveSecondOrder(a2, a1, a0 Poly) (RatFunc, KovacicResult, error)

KovacicSolveSecondOrder is a convenience wrapper that reduces the general second-order equation a2 y” + a1 y' + a0 y = 0 to normal form and runs the Kovacic algorithm, returning both the reduced r and the result.

func LinearlyIndependentPoly

func LinearlyIndependentPoly(ps []Poly) bool

LinearlyIndependentPoly reports whether the polynomials are linearly independent over Q, tested by a non-vanishing Wronskian.

func LinearlyIndependentRatFunc

func LinearlyIndependentRatFunc(fs []RatFunc) bool

LinearlyIndependentRatFunc reports whether the rational functions are linearly independent over the constants, tested by a non-vanishing Wronskian.

func RatFromFloat

func RatFromFloat(f float64) *big.Rat

RatFromFloat returns the exact rational value of the IEEE-754 float f. It returns nil if f is not finite.

func RatFromFrac

func RatFromFrac(p, q int64) *big.Rat

RatFromFrac returns the rational number p/q. It panics only if q is zero, matching the behaviour of math/big.NewRat.

func RatFromInt

func RatFromInt(n int64) *big.Rat

RatFromInt returns the rational number n/1.

func RatFromString

func RatFromString(s string) (*big.Rat, bool)

RatFromString parses a rational number written as "p/q", a decimal, or an integer. It reports whether parsing succeeded.

func RatString

func RatString(r *big.Rat) string

RatString formats r as "p/q" (or "p" when the denominator is one).

func RatToFloat

func RatToFloat(r *big.Rat) float64

RatToFloat returns the nearest float64 to r.

func RecurrenceValues

func RecurrenceValues(coeffs []float64, seeds []float64, count int) ([]float64, error)

RecurrenceValues iterates the recurrence directly to produce the first count terms from the given seed values, for cross-checking a closed-form solution. coeffs must be normalised so that the highest-order term can be solved for; it returns ErrDegree if the leading coefficient is zero and ErrDim if seeds does not provide order-1 initial values.

func StructureTheoremExp

func StructureTheoremExp(f, g Poly) (string, bool)

StructureTheoremExp applies the Risch structure-theorem heuristic to decide whether f e^{g} is elementary and returns a human-readable description of the antiderivative or the reason it is not elementary.

func WronskianMatrixPoly

func WronskianMatrixPoly(ps []Poly) [][]Poly

WronskianMatrixPoly returns the Wronskian matrix of the polynomials ps.

func WronskianMatrixRatFunc

func WronskianMatrixRatFunc(fs []RatFunc) [][]RatFunc

WronskianMatrixRatFunc returns the Wronskian matrix of the functions fs: row i holds the (i)-th derivatives of every function.

Types

type Derivation

type Derivation struct{}

Derivation is the standard derivation d/dx on the differential field Q(x). It is a value type carrying no configuration; the zero value is ready to use and StandardDerivation is provided for readability.

func StandardDerivation

func StandardDerivation() Derivation

StandardDerivation returns the derivation d/dx on Q(x).

func (Derivation) Apply

func (Derivation) Apply(f RatFunc) RatFunc

Apply returns the derivative of a rational function.

func (Derivation) ApplyN

func (d Derivation) ApplyN(f RatFunc, n int) RatFunc

ApplyN returns the n-th derivative of a rational function (n >= 0).

func (Derivation) ApplyNPoly

func (d Derivation) ApplyNPoly(p Poly, n int) Poly

ApplyNPoly returns the n-th derivative of a polynomial (n >= 0).

func (Derivation) ApplyPoly

func (Derivation) ApplyPoly(p Poly) Poly

ApplyPoly returns the derivative of a polynomial.

func (Derivation) ConstantField

func (d Derivation) ConstantField(f RatFunc) bool

ConstantField reports whether every element derived from f by the derivation eventually vanishes; for Q(x) this is equivalent to f being constant.

func (Derivation) IsConstant

func (d Derivation) IsConstant(f RatFunc) bool

IsConstant reports whether f lies in the kernel of the derivation, i.e. f is a constant of Q(x).

func (Derivation) Leibniz

func (d Derivation) Leibniz(f, g RatFunc) (direct, leibniz RatFunc)

Leibniz verifies the product rule for two rational functions, returning D(fg) computed both directly and via the Leibniz expansion f'g + fg'; the two are always equal and this is provided as a self-checking utility.

func (Derivation) LogarithmicDerivative

func (d Derivation) LogarithmicDerivative(f RatFunc) (RatFunc, error)

LogarithmicDerivative returns f'/f, the logarithmic derivative of f.

type ExpIntegrand

type ExpIntegrand struct {
	Coeff Poly // f(x)
	Arg   Poly // g(x)
}

ExpIntegrand pairs a polynomial coefficient with an exponential argument, representing f(x) e^{g(x)}.

func (ExpIntegrand) EvalFloat

func (e ExpIntegrand) EvalFloat(x float64) (float64, bool)

EvalFloat evaluates the elementary antiderivative R(x) e^{g(x)} at x, when it exists; the second return reports elementary integrability.

func (ExpIntegrand) Integrate

func (e ExpIntegrand) Integrate() (Poly, bool)

Integrate returns the polynomial R such that the antiderivative equals R(x) e^{Arg(x)}, together with whether the integrand is elementary.

type KovacicPole

type KovacicPole struct {
	C     *big.Rat
	Order int
	B     *big.Rat
}

KovacicPole describes a rational pole c of r together with its order and the leading Laurent coefficient b (the coefficient of 1/(x-c)^order).

func (KovacicPole) String

func (p KovacicPole) String() string

String renders a pole for diagnostics.

type KovacicResult

type KovacicResult struct {
	Found   bool
	Case    int
	R       RatFunc
	Omega   RatFunc
	P       Poly
	ExpLogs []LogTerm
}

KovacicResult is the outcome of the Kovacic algorithm for y” = r y. When Found is true a Liouvillian solution y = P(x) exp(integral Omega) was constructed (Case 1), with ExpLogs giving integral(Omega) as a sum of logarithms.

func Kovacic

func Kovacic(r RatFunc) (KovacicResult, error)

Kovacic runs Case 1 of the Kovacic algorithm on y” = r y, attempting to construct a Liouvillian solution y = P exp(integral omega). It handles rational poles of order at most two and order at infinity at least two. When no such solution is found it returns a result with Found == false and a nil error; structural obstructions (non-rational poles, unsupported orders) likewise yield Found == false.

func (KovacicResult) EvalFloat

func (k KovacicResult) EvalFloat(x float64) float64

EvalFloat evaluates the constructed solution at x, using |x-c| inside the logarithms; it returns 0 when no solution was found.

func (KovacicResult) SolutionString

func (k KovacicResult) SolutionString() string

SolutionString renders the constructed solution y = P * exp(integral Omega).

type LogTerm

type LogTerm struct {
	Coeff *big.Rat
	Arg   Poly
}

LogTerm is a summand Coeff * log(Arg) of the logarithmic part of an integral, where Coeff is a rational residue and Arg is a monic polynomial.

func (LogTerm) String

func (t LogTerm) String() string

String renders the log term as "c*log(arg)".

type ODESolution

type ODESolution struct {
	Terms []ODETerm
	Roots []RootCluster
}

ODESolution is the general homogeneous solution of a constant-coefficient linear ODE, described by its fundamental system of basis terms and the characteristic root clusters.

func SolveLinearConstantODE

func SolveLinearConstantODE(coeffs []float64, seed int64, tol float64) (ODESolution, error)

SolveLinearConstantODE builds the general solution of the homogeneous constant-coefficient linear ODE sum_i coeffs[i] y^(i) = 0, where coeffs[i] is the real coefficient of the i-th derivative. The characteristic roots are found numerically (seeded) and clustered into multiplicities using tol. It returns ErrDegree when the leading coefficient is zero or the equation is trivial.

func SolveODEIVP

func SolveODEIVP(coeffs []float64, x0 float64, ic []float64, seed int64, tol float64) ([]float64, ODESolution, error)

SolveODEIVP solves the initial-value problem for the homogeneous constant-coefficient ODE sum_i coeffs[i] y^(i) = 0 with the initial data ic[d] = y^(d)(x0) for d = 0..n-1. It returns the fitted constants together with the general solution. It returns ErrDim when len(ic) does not match the order and ErrSingular when the Wronskian system is singular.

func (ODESolution) Basis

func (s ODESolution) Basis() []ODETerm

Basis returns the fundamental system of basis terms.

func (ODESolution) Dimension

func (s ODESolution) Dimension() int

Dimension returns the number of basis solutions (the order of the ODE).

func (ODESolution) EvalBasis

func (s ODESolution) EvalBasis(x float64) []float64

EvalBasis returns the values of every basis term at x.

func (ODESolution) Evaluate

func (s ODESolution) Evaluate(consts []float64, x float64) float64

Evaluate returns sum_i consts[i] * basis_i(x). It panics only when consts has the wrong length is avoided by treating missing constants as zero.

func (ODESolution) String

func (s ODESolution) String() string

String renders the general solution as a linear combination C1*..+C2*.. .

type ODETerm

type ODETerm struct {
	Kind  ODETermKind
	Power int
	Alpha float64
	Beta  float64
}

ODETerm is one basis solution of a constant-coefficient linear ODE, of the form x^Power * e^{Alpha x} * trig(Beta x).

func (ODETerm) Eval

func (t ODETerm) Eval(x float64) float64

Eval returns the value of the basis term at x.

func (ODETerm) String

func (t ODETerm) String() string

String renders the term in readable form.

type ODETermKind

type ODETermKind int

ODETermKind classifies a basis solution of a constant-coefficient linear ODE.

const (
	// RealExp is a term x^k e^{alpha x} coming from a real characteristic root.
	RealExp ODETermKind = iota
	// ComplexCos is a term x^k e^{alpha x} cos(beta x) from a complex pair.
	ComplexCos
	// ComplexSin is a term x^k e^{alpha x} sin(beta x) from a complex pair.
	ComplexSin
)

type Operator

type Operator struct {
	// contains filtered or unexported fields
}

Operator is a linear differential operator sum_i a_i(x) D^i with rational-function coefficients, an element of the non-commutative Ore ring Q(x)[D] with the multiplication rule D*a = a*D + a'. Coefficient i multiplies D^i; the slice is kept trimmed of trailing zero coefficients.

func ConstOperator

func ConstOperator(a RatFunc) Operator

ConstOperator returns the zeroth-order operator that multiplies by the rational function a.

func DOperator

func DOperator() Operator

DOperator returns the derivation operator D itself.

func IdentityOperator

func IdentityOperator() Operator

IdentityOperator returns the identity operator (multiplication by 1).

func NewOperator

func NewOperator(coeffs ...RatFunc) Operator

NewOperator builds an operator from coefficients in ascending order of D (coeffs[0] is the zeroth-order term).

func OperatorFromPolys

func OperatorFromPolys(coeffs ...Poly) Operator

OperatorFromPolys builds an operator whose coefficients are the given polynomials, in ascending order of D.

func ZeroOperator

func ZeroOperator() Operator

ZeroOperator returns the zero operator.

func (Operator) Add

func (o Operator) Add(p Operator) Operator

Add returns o+p.

func (Operator) Adjoint

func (o Operator) Adjoint() Operator

Adjoint returns the formal adjoint operator L^* defined by L^*(y) = sum_i (-1)^i (a_i y)^(i), obtained by the standard alternating-sign transpose.

func (Operator) ApplyPoly

func (o Operator) ApplyPoly(y Poly) RatFunc

ApplyPoly applies the operator to a polynomial y.

func (Operator) ApplyRatFunc

func (o Operator) ApplyRatFunc(y RatFunc) RatFunc

ApplyRatFunc applies the operator to a rational function y, returning sum_i a_i y^(i).

func (Operator) Coeff

func (o Operator) Coeff(i int) RatFunc

Coeff returns the coefficient of D^i, or zero when out of range.

func (Operator) Coeffs

func (o Operator) Coeffs() []RatFunc

Coeffs returns a copy of the coefficient slice in ascending order of D.

func (Operator) Equal

func (o Operator) Equal(p Operator) bool

Equal reports whether o and p are equal operators.

func (Operator) IndicialPolynomial

func (o Operator) IndicialPolynomial() (Poly, bool)

IndicialPolynomial returns the indicial polynomial at the ordinary point x=0 for an operator with polynomial coefficients, computed from the lowest-order behaviour. It returns the polynomial whose roots are the indicial exponents and reports false when the operator does not have the required form.

func (Operator) IsZero

func (o Operator) IsZero() bool

IsZero reports whether o is the zero operator.

func (Operator) LeadingCoeff

func (o Operator) LeadingCoeff() RatFunc

LeadingCoeff returns the coefficient of the highest-order term.

func (Operator) Mul

func (o Operator) Mul(p Operator) Operator

Mul returns the composition o∘p in the Ore ring, using D*a = a*D + a'.

func (Operator) Neg

func (o Operator) Neg() Operator

Neg returns -o.

func (Operator) Order

func (o Operator) Order() int

Order returns the order (highest power of D) of the operator; the zero operator has order -1.

func (Operator) Pow

func (o Operator) Pow(n int) Operator

Pow raises the operator to the non-negative integer power n (composition).

func (Operator) ScalarMul

func (o Operator) ScalarMul(a RatFunc) Operator

ScalarMul multiplies o on the left by the rational function a (a*o).

func (Operator) String

func (o Operator) String() string

String renders the operator in descending order of D.

func (Operator) Sub

func (o Operator) Sub(p Operator) Operator

Sub returns o-p.

func (Operator) SymbolPoly

func (o Operator) SymbolPoly() (Poly, bool)

SymbolPoly returns the symbol of the operator: the polynomial in a formal variable obtained by replacing D^i with the i-th power and freezing the coefficients at the rational point x. It is used to read off the principal part; here it returns the leading coefficient's numerator scaled form as a Poly in D with the coefficients evaluated is not well defined over Q(x), so instead SymbolPoly returns the vector of coefficients as a Poly when the operator has polynomial coefficients.

type PartialFractionTerm

type PartialFractionTerm struct {
	Numerator Poly
	Factor    Poly
	Power     int
}

PartialFractionTerm is a summand A/(F^k) of a partial-fraction decomposition, where F is a monic square-free polynomial appearing to power Power and deg(Numerator) < deg(F).

type Poly

type Poly struct {
	// contains filtered or unexported fields
}

Poly is a dense univariate polynomial over the rational numbers Q. The zero polynomial is represented by an empty coefficient slice. Coefficient i is the coefficient of x^i; the slice is always kept in normalised form with no trailing (highest-degree) zero coefficients.

func ConstPoly

func ConstPoly(r *big.Rat) Poly

ConstPoly returns the constant polynomial equal to r.

func ConstPolyInt

func ConstPolyInt(n int64) Poly

ConstPolyInt returns the constant polynomial equal to the integer n.

func DeterminantPoly

func DeterminantPoly(m [][]Poly) (Poly, error)

DeterminantPoly returns the determinant of a square matrix of polynomials by evaluating over the field Q(x). It returns a polynomial when the true determinant is a polynomial (which is always the case for a polynomial matrix).

func Monomial

func Monomial(coeff *big.Rat, deg int) Poly

Monomial returns the polynomial coeff * x^deg.

func NewPoly

func NewPoly(coeffs ...*big.Rat) Poly

NewPoly builds a polynomial from coefficients given in ascending degree order (coeffs[0] is the constant term). The inputs are copied.

func OnePoly

func OnePoly() Poly

OnePoly returns the constant polynomial 1.

func PolyFromInts

func PolyFromInts(coeffs ...int64) Poly

PolyFromInts builds a polynomial from integer coefficients in ascending degree order.

func RischExpIntegrate

func RischExpIntegrate(f, g Poly) (Poly, bool)

RischExpIntegrate decides whether the integrand f(x) e^{g(x)} has an elementary antiderivative for polynomials f and g, and if so returns the polynomial R with integral = R(x) e^{g(x)}. It solves the Risch differential equation R' + g' R = f. The boolean reports elementary integrability.

Example
// Integrate 2x * e^(x^2): result is 1 * e^(x^2).
R, ok := RischExpIntegrate(PolyFromInts(0, 2), PolyFromInts(0, 0, 1))
fmt.Println(R, ok)
Output:
1 true

func RothsteinTragerResultant

func RothsteinTragerResultant(f RatFunc) Poly

RothsteinTragerResultant returns the Rothstein-Trager resultant R(z) = Res_x(D, C - z D') for the square-free proper integrand C/D, whose rational roots are the residues of the logarithmic part.

func SolveRischDE

func SolveRischDE(a, b Poly) (Poly, bool)

SolveRischDE solves the Risch differential equation R' + a R = b for a polynomial R, given polynomials a and b. It returns the polynomial solution and true when one exists, or false when no polynomial solution exists. This is the core sub-algorithm used to decide elementary integrability of exponential integrands.

func WronskianPoly

func WronskianPoly(ps []Poly) (Poly, error)

WronskianPoly returns the Wronskian determinant of the polynomials ps.

func XPoly

func XPoly() Poly

XPoly returns the polynomial x.

func ZeroPoly

func ZeroPoly() Poly

ZeroPoly returns the zero polynomial.

func (Poly) Add

func (p Poly) Add(q Poly) Poly

Add returns p+q.

func (Poly) Clone

func (p Poly) Clone() Poly

Clone returns a deep copy of p.

func (Poly) Coeff

func (p Poly) Coeff(i int) *big.Rat

Coeff returns the coefficient of x^i, or zero when i is out of range.

func (Poly) Coeffs

func (p Poly) Coeffs() []*big.Rat

Coeffs returns a fresh slice of the coefficients in ascending degree order.

func (Poly) ComplexRootsFloat

func (p Poly) ComplexRootsFloat(seed int64) []complex128

ComplexRootsFloat returns the roots of p as complex numbers using the Durand-Kerner iteration seeded by the given value. The zero polynomial and constants return nil.

func (Poly) Compose

func (p Poly) Compose(q Poly) Poly

Compose returns p(q(x)).

func (Poly) ConstantTerm

func (p Poly) ConstantTerm() *big.Rat

ConstantTerm returns the coefficient of x^0.

func (Poly) Content

func (p Poly) Content() *big.Rat

Content returns the (positive) rational content of p: the gcd of the integer numerators divided by the lcm of the denominators. It returns zero for the zero polynomial.

func (Poly) Degree

func (p Poly) Degree() int

Degree returns the degree of p. The zero polynomial has degree -1.

func (Poly) Derivative

func (p Poly) Derivative() Poly

Derivative returns the formal derivative dp/dx.

func (Poly) Discriminant

func (p Poly) Discriminant() *big.Rat

Discriminant returns the discriminant of p, defined via the resultant of p and its derivative.

func (Poly) DivMod

func (p Poly) DivMod(d Poly) (q, r Poly, err error)

DivMod returns the quotient and remainder of Euclidean division p = q*d + r with deg r < deg d. It returns ErrDivByZero when d is zero.

func (Poly) Equal

func (p Poly) Equal(q Poly) bool

Equal reports whether p and q are equal as polynomials.

func (Poly) EvalComplex

func (p Poly) EvalComplex(z complex128) complex128

EvalComplex evaluates p at the complex point z.

func (Poly) EvalFloat

func (p Poly) EvalFloat(x float64) float64

EvalFloat evaluates p at the floating-point point x.

func (Poly) EvalRat

func (p Poly) EvalRat(x *big.Rat) *big.Rat

EvalRat evaluates p at the rational point x using Horner's rule.

func (Poly) ExtendedGCD

func (p Poly) ExtendedGCD(q Poly) (g, s, t Poly)

ExtendedGCD returns the monic gcd g of p and q together with cofactors s and t satisfying s*p + t*q = g.

func (Poly) GCD

func (p Poly) GCD(q Poly) Poly

GCD returns the monic greatest common divisor of p and q. The GCD of two zero polynomials is zero.

func (Poly) Integral

func (p Poly) Integral() Poly

Integral returns the antiderivative of p with zero constant of integration.

func (Poly) IsConstant

func (p Poly) IsConstant() bool

IsConstant reports whether p has degree at most zero.

func (Poly) IsMonic

func (p Poly) IsMonic() bool

IsMonic reports whether p is monic.

func (Poly) IsZero

func (p Poly) IsZero() bool

IsZero reports whether p is the zero polynomial.

func (Poly) LeadingCoeff

func (p Poly) LeadingCoeff() *big.Rat

LeadingCoeff returns the coefficient of the highest-degree term, or zero for the zero polynomial.

func (Poly) Monic

func (p Poly) Monic() Poly

Monic returns p scaled to be monic (leading coefficient 1). The zero polynomial is returned unchanged.

func (Poly) Mul

func (p Poly) Mul(q Poly) Poly

Mul returns p*q.

func (Poly) Neg

func (p Poly) Neg() Poly

Neg returns -p.

func (Poly) PolyComplexRootClusters

func (p Poly) PolyComplexRootClusters(seed int64, tol float64) []RootCluster

PolyComplexRootClusters returns the clustered roots of p with inferred multiplicities, using tol to merge coincident roots.

func (Poly) Pow

func (p Poly) Pow(n int) Poly

Pow returns p raised to the non-negative integer power n.

func (Poly) PrimitivePart

func (p Poly) PrimitivePart() Poly

PrimitivePart returns p divided by its content, so the result has integer coprime coefficients and positive leading sign preserved.

func (Poly) Quo

func (p Poly) Quo(d Poly) (Poly, error)

Quo returns the quotient of p divided by d (see DivMod).

func (Poly) RationalRoots

func (p Poly) RationalRoots() []*big.Rat

RationalRoots returns all distinct rational roots of p (without multiplicity) using the rational-root theorem. The zero polynomial yields nil.

func (Poly) Rem

func (p Poly) Rem(d Poly) (Poly, error)

Rem returns the remainder of p divided by d (see DivMod).

func (Poly) Resultant

func (p Poly) Resultant(q Poly) *big.Rat

Resultant returns the resultant Res(p, q) computed with the Euclidean recurrence. It is zero exactly when p and q share a non-constant factor.

func (Poly) Reverse

func (p Poly) Reverse() Poly

Reverse returns the reversal x^deg * p(1/x), i.e. p with its coefficient list reversed.

func (Poly) ScalarMul

func (p Poly) ScalarMul(r *big.Rat) Poly

ScalarMul returns r*p for a rational scalar r.

func (Poly) Shift

func (p Poly) Shift(a *big.Rat) Poly

Shift returns p(x + a) for a rational shift a.

func (Poly) SquareFreeFactorization

func (p Poly) SquareFreeFactorization() []SquareFreeFactor

SquareFreeFactorization returns the square-free factorisation of p using Yun's algorithm. The returned factors are monic, pairwise coprime and square-free, and their product raised to the listed multiplicities equals the monic part of p. Constant and zero inputs yield an empty slice.

func (Poly) SquareFreePart

func (p Poly) SquareFreePart() Poly

SquareFreePart returns the square-free part of p, namely p / gcd(p, p').

func (Poly) String

func (p Poly) String() string

String renders p in descending-degree human-readable form, e.g. "x^2 - 2".

func (Poly) Sub

func (p Poly) Sub(q Poly) Poly

Sub returns p-q.

type RatFunc

type RatFunc struct {
	// contains filtered or unexported fields
}

RatFunc is a rational function p/q over Q, kept in reduced form with a monic denominator. The zero rational function has numerator zero and denominator one.

func ConstRatFunc

func ConstRatFunc(r *big.Rat) RatFunc

ConstRatFunc returns the constant rational function equal to r.

func DeterminantRatFunc

func DeterminantRatFunc(m [][]RatFunc) (RatFunc, error)

DeterminantRatFunc returns the determinant of a square matrix of rational functions using fraction-free-free Gaussian elimination over the field Q(x). It returns ErrNotSquare for a non-square input and ErrEmpty for an empty one.

func LogarithmicDerivativeIsRational

func LogarithmicDerivativeIsRational(f RatFunc) (RatFunc, bool)

LogarithmicDerivativeIsRational reports whether the logarithmic derivative of a rational function f is again a proper rational function whose partial fraction has only simple poles, the structural signature of a logarithm. It returns the logarithmic derivative and the verdict.

func NewRatFunc

func NewRatFunc(num, den Poly) (RatFunc, error)

NewRatFunc builds the reduced rational function num/den. It returns ErrDivByZero when den is the zero polynomial.

func OneRatFunc

func OneRatFunc() RatFunc

OneRatFunc returns the constant rational function 1.

func RatFuncFromPoly

func RatFuncFromPoly(p Poly) RatFunc

RatFuncFromPoly returns the rational function p/1.

func ReduceToNormalForm

func ReduceToNormalForm(a2, a1, a0 Poly) (RatFunc, error)

ReduceToNormalForm converts the second-order linear ODE a2 y” + a1 y' + a0 y = 0 into the reduced normal form z” = r z, returning r as a rational function. The substitution is y = z * exp(-1/2 integral(a1/a2)). It returns ErrDivByZero when a2 is the zero polynomial.

func VariationOfParameters

func VariationOfParameters(ys []RatFunc, g RatFunc) (RatFunc, error)

VariationOfParameters attempts to build a particular solution of the monic linear ODE L[y] = g from the fundamental system ys by integrating the variation-of-parameters integrands. It succeeds when every integrand integrates to a rational function (no logarithmic part); otherwise it returns ErrNoSolution together with the integrands via VariationOfParametersIntegrands. The returned RatFunc is the particular solution y_p.

func VariationOfParametersIntegrands

func VariationOfParametersIntegrands(ys []RatFunc, g RatFunc) ([]RatFunc, error)

VariationOfParametersIntegrands returns the derivatives u_i'(x) of the variation-of-parameters coefficient functions for the monic linear ODE L[y] = g whose fundamental system is ys and whose forcing term is g. The particular solution is y_p = sum_i (integral of u_i') * y_i. It returns ErrEmpty for no fundamental solutions and ErrSingular when the Wronskian vanishes identically.

func WronskianRatFunc

func WronskianRatFunc(fs []RatFunc) (RatFunc, error)

WronskianRatFunc returns the Wronskian determinant of the rational functions fs. An empty input returns ErrEmpty.

func XRatFunc

func XRatFunc() RatFunc

XRatFunc returns the rational function x.

func ZeroRatFunc

func ZeroRatFunc() RatFunc

ZeroRatFunc returns the zero rational function.

func (RatFunc) Add

func (f RatFunc) Add(g RatFunc) RatFunc

Add returns f+g.

func (RatFunc) Den

func (f RatFunc) Den() Poly

Den returns a copy of the denominator.

func (RatFunc) Derivative

func (f RatFunc) Derivative() RatFunc

Derivative returns the derivative df/dx via the quotient rule.

func (RatFunc) Div

func (f RatFunc) Div(g RatFunc) (RatFunc, error)

Div returns f/g. It returns ErrDivByZero when g is zero.

func (RatFunc) Equal

func (f RatFunc) Equal(g RatFunc) bool

Equal reports whether f and g are equal as rational functions.

func (RatFunc) EvalComplex

func (f RatFunc) EvalComplex(z complex128) complex128

EvalComplex evaluates f at the complex point z.

func (RatFunc) EvalFloat

func (f RatFunc) EvalFloat(x float64) float64

EvalFloat evaluates f at the floating-point point x.

func (RatFunc) EvalRat

func (f RatFunc) EvalRat(x *big.Rat) (*big.Rat, error)

EvalRat evaluates f at the rational point x. It returns ErrDivByZero when the denominator vanishes there.

func (RatFunc) Inv

func (f RatFunc) Inv() (RatFunc, error)

Inv returns 1/f. It returns ErrDivByZero when f is zero.

func (RatFunc) IsPolynomial

func (f RatFunc) IsPolynomial() bool

IsPolynomial reports whether the denominator is a constant.

func (RatFunc) IsProper

func (f RatFunc) IsProper() bool

IsProper reports whether deg(num) < deg(den).

func (RatFunc) IsZero

func (f RatFunc) IsZero() bool

IsZero reports whether f is the zero rational function.

func (RatFunc) LogDerivative

func (f RatFunc) LogDerivative() (RatFunc, error)

LogDerivative returns the logarithmic derivative f'/f. It returns ErrDivByZero when f is zero.

func (RatFunc) Mul

func (f RatFunc) Mul(g RatFunc) RatFunc

Mul returns f*g.

func (RatFunc) Neg

func (f RatFunc) Neg() RatFunc

Neg returns -f.

func (RatFunc) Num

func (f RatFunc) Num() Poly

Num returns a copy of the numerator.

func (RatFunc) PartialFractions

func (f RatFunc) PartialFractions() (Poly, []PartialFractionTerm)

PartialFractions returns the polynomial part together with the partial-fraction terms of f over Q, grouping the denominator by its square-free factorisation and reducing each power. The decomposition is exact over Q (residues that would be irrational are left folded inside the numerator over the corresponding square-free factor).

func (RatFunc) PolynomialPart

func (f RatFunc) PolynomialPart() (quotient Poly, remainder RatFunc)

PolynomialPart returns the polynomial quotient and proper remainder so that f = quotient + remainder with the remainder proper.

func (RatFunc) Pow

func (f RatFunc) Pow(n int) (RatFunc, error)

Pow raises f to the integer power n (n may be negative). A negative power of the zero function returns ErrDivByZero.

func (RatFunc) ScalarMul

func (f RatFunc) ScalarMul(r *big.Rat) RatFunc

ScalarMul returns r*f for a rational scalar r.

func (RatFunc) String

func (f RatFunc) String() string

String renders f as "(num)/(den)" or just the numerator when polynomial.

func (RatFunc) Sub

func (f RatFunc) Sub(g RatFunc) RatFunc

Sub returns f-g.

type RationalIntegral

type RationalIntegral struct {
	Rational            RatFunc
	Logs                []LogTerm
	ResidueResultant    Poly
	AllResiduesRational bool
}

RationalIntegral is the result of integrating a rational function: an elementary rational part plus a sum of logarithm terms. When some residue is not rational, AllResiduesRational is false and ResidueResultant holds the Rothstein-Trager resultant whose roots are the residues.

func IntegrateRational

func IntegrateRational(f RatFunc) (RationalIntegral, error)

IntegrateRational returns the elementary integral of the rational function f, as a rational part plus a sum of logarithms with rational coefficients. Every rational function has an elementary integral; when a residue happens to be irrational the corresponding logarithm is omitted from Logs and AllResiduesRational is reported false, with ResidueResultant describing the remaining residues.

Example
// Integrate 1/(x^2 - 1) over Q.
f, _ := NewRatFunc(OnePoly(), PolyFromInts(-1, 0, 1))
res, _ := IntegrateRational(f)
fmt.Println(res)
Output:
1/2*log(x - 1) + -1/2*log(x + 1)

func (RationalIntegral) EvalFloat

func (r RationalIntegral) EvalFloat(x float64) float64

EvalFloat evaluates the integral numerically at x, using log|Arg| for the logarithmic terms. It is intended for cross-checking against numerical quadrature.

func (RationalIntegral) String

func (r RationalIntegral) String() string

String renders the integral as its rational part followed by its log terms.

type RecurrenceSolution

type RecurrenceSolution struct {
	Terms []RecurrenceTerm
	Roots []RootCluster
}

RecurrenceSolution is the general solution of a constant-coefficient linear recurrence, described by its fundamental basis terms and characteristic root clusters.

func SolveLinearRecurrence

func SolveLinearRecurrence(coeffs []float64, seed int64, tol float64) (RecurrenceSolution, error)

SolveLinearRecurrence builds the general solution of the homogeneous constant-coefficient linear recurrence sum_i coeffs[i] a_{n+i} = 0, where coeffs[i] is the real coefficient of a_{n+i}. The characteristic roots are found numerically (seeded) and clustered into multiplicities using tol. It returns ErrDegree when the recurrence has order below one.

Example
// Fibonacci recurrence a_{n+2} = a_{n+1} + a_n with a_0=0, a_1=1.
coeffs := []float64{-1, -1, 1}
c, sol, _ := SolveRecurrenceIVP(coeffs, []float64{0, 1}, 1, 1e-6)
fmt.Printf("a_10 = %.0f\n", sol.Evaluate(c, 10))
Output:
a_10 = 55

func SolveRecurrenceIVP

func SolveRecurrenceIVP(coeffs []float64, initial []float64, seed int64, tol float64) ([]float64, RecurrenceSolution, error)

SolveRecurrenceIVP fits the constants of the general solution to the initial data initial[i] = a_i for i = 0..order-1. It returns the fitted constants together with the general solution. It returns ErrDim when len(initial) does not match the order and ErrSingular when the fitting matrix is singular.

func (RecurrenceSolution) Basis

func (s RecurrenceSolution) Basis() []RecurrenceTerm

Basis returns the fundamental basis terms.

func (RecurrenceSolution) Dimension

func (s RecurrenceSolution) Dimension() int

Dimension returns the number of basis terms (the order of the recurrence).

func (RecurrenceSolution) EvalBasis

func (s RecurrenceSolution) EvalBasis(n int) []float64

EvalBasis returns the values of every basis term at index n.

func (RecurrenceSolution) Evaluate

func (s RecurrenceSolution) Evaluate(consts []float64, n int) float64

Evaluate returns sum_i consts[i] * basis_i(n).

func (RecurrenceSolution) String

func (s RecurrenceSolution) String() string

String renders the general solution as a linear combination.

type RecurrenceTerm

type RecurrenceTerm struct {
	Kind  RecurrenceTermKind
	Power int
	Rho   float64 // signed root for real terms, modulus for complex terms
	Theta float64
}

RecurrenceTerm is one basis solution of a linear recurrence, of the form n^Power * Rho^n * trig(n*Theta) (with Theta zero for real roots, in which case Rho carries the sign of the root).

func (RecurrenceTerm) Eval

func (t RecurrenceTerm) Eval(n int) float64

Eval returns the value of the basis term at integer index n.

func (RecurrenceTerm) String

func (t RecurrenceTerm) String() string

String renders the recurrence basis term.

type RecurrenceTermKind

type RecurrenceTermKind int

RecurrenceTermKind classifies a basis solution of a constant-coefficient linear recurrence.

const (
	// RealGeom is a term n^k lambda^n from a real characteristic root.
	RealGeom RecurrenceTermKind = iota
	// ComplexGeomCos is a term n^k rho^n cos(n theta) from a complex pair.
	ComplexGeomCos
	// ComplexGeomSin is a term n^k rho^n sin(n theta) from a complex pair.
	ComplexGeomSin
)

type RootCluster

type RootCluster struct {
	Value complex128
	Mult  int
}

RootCluster is a complex root together with the multiplicity inferred by grouping numerically coincident roots.

type SquareFreeFactor

type SquareFreeFactor struct {
	Factor Poly
	Mult   int
}

SquareFreeFactor is one factor of a square-free factorisation: the monic square-free polynomial Factor appears to the power Mult in the original.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL