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 ¶
- Variables
- func CharacteristicComplexRoots(coeffs []float64, seed int64) []complex128
- func HermiteReduce(f RatFunc) (rational RatFunc, remaining RatFunc)
- func KovacicSolveSecondOrder(a2, a1, a0 Poly) (RatFunc, KovacicResult, error)
- func LinearlyIndependentPoly(ps []Poly) bool
- func LinearlyIndependentRatFunc(fs []RatFunc) bool
- func RatFromFloat(f float64) *big.Rat
- func RatFromFrac(p, q int64) *big.Rat
- func RatFromInt(n int64) *big.Rat
- func RatFromString(s string) (*big.Rat, bool)
- func RatString(r *big.Rat) string
- func RatToFloat(r *big.Rat) float64
- func RecurrenceValues(coeffs []float64, seeds []float64, count int) ([]float64, error)
- func StructureTheoremExp(f, g Poly) (string, bool)
- func WronskianMatrixPoly(ps []Poly) [][]Poly
- func WronskianMatrixRatFunc(fs []RatFunc) [][]RatFunc
- type Derivation
- func (Derivation) Apply(f RatFunc) RatFunc
- func (d Derivation) ApplyN(f RatFunc, n int) RatFunc
- func (d Derivation) ApplyNPoly(p Poly, n int) Poly
- func (Derivation) ApplyPoly(p Poly) Poly
- func (d Derivation) ConstantField(f RatFunc) bool
- func (d Derivation) IsConstant(f RatFunc) bool
- func (d Derivation) Leibniz(f, g RatFunc) (direct, leibniz RatFunc)
- func (d Derivation) LogarithmicDerivative(f RatFunc) (RatFunc, error)
- type ExpIntegrand
- type KovacicPole
- type KovacicResult
- type LogTerm
- type ODESolution
- type ODETerm
- type ODETermKind
- type Operator
- func (o Operator) Add(p Operator) Operator
- func (o Operator) Adjoint() Operator
- func (o Operator) ApplyPoly(y Poly) RatFunc
- func (o Operator) ApplyRatFunc(y RatFunc) RatFunc
- func (o Operator) Coeff(i int) RatFunc
- func (o Operator) Coeffs() []RatFunc
- func (o Operator) Equal(p Operator) bool
- func (o Operator) IndicialPolynomial() (Poly, bool)
- func (o Operator) IsZero() bool
- func (o Operator) LeadingCoeff() RatFunc
- func (o Operator) Mul(p Operator) Operator
- func (o Operator) Neg() Operator
- func (o Operator) Order() int
- func (o Operator) Pow(n int) Operator
- func (o Operator) ScalarMul(a RatFunc) Operator
- func (o Operator) String() string
- func (o Operator) Sub(p Operator) Operator
- func (o Operator) SymbolPoly() (Poly, bool)
- type PartialFractionTerm
- type Poly
- func ConstPoly(r *big.Rat) Poly
- func ConstPolyInt(n int64) Poly
- func DeterminantPoly(m [][]Poly) (Poly, error)
- func Monomial(coeff *big.Rat, deg int) Poly
- func NewPoly(coeffs ...*big.Rat) Poly
- func OnePoly() Poly
- func PolyFromInts(coeffs ...int64) Poly
- func RischExpIntegrate(f, g Poly) (Poly, bool)
- func RothsteinTragerResultant(f RatFunc) Poly
- func SolveRischDE(a, b Poly) (Poly, bool)
- func WronskianPoly(ps []Poly) (Poly, error)
- func XPoly() Poly
- func ZeroPoly() Poly
- func (p Poly) Add(q Poly) Poly
- func (p Poly) Clone() Poly
- func (p Poly) Coeff(i int) *big.Rat
- func (p Poly) Coeffs() []*big.Rat
- func (p Poly) ComplexRootsFloat(seed int64) []complex128
- func (p Poly) Compose(q Poly) Poly
- func (p Poly) ConstantTerm() *big.Rat
- func (p Poly) Content() *big.Rat
- func (p Poly) Degree() int
- func (p Poly) Derivative() Poly
- func (p Poly) Discriminant() *big.Rat
- func (p Poly) DivMod(d Poly) (q, r Poly, err error)
- func (p Poly) Equal(q Poly) bool
- func (p Poly) EvalComplex(z complex128) complex128
- func (p Poly) EvalFloat(x float64) float64
- func (p Poly) EvalRat(x *big.Rat) *big.Rat
- func (p Poly) ExtendedGCD(q Poly) (g, s, t Poly)
- func (p Poly) GCD(q Poly) Poly
- func (p Poly) Integral() Poly
- func (p Poly) IsConstant() bool
- func (p Poly) IsMonic() bool
- func (p Poly) IsZero() bool
- func (p Poly) LeadingCoeff() *big.Rat
- func (p Poly) Monic() Poly
- func (p Poly) Mul(q Poly) Poly
- func (p Poly) Neg() Poly
- func (p Poly) PolyComplexRootClusters(seed int64, tol float64) []RootCluster
- func (p Poly) Pow(n int) Poly
- func (p Poly) PrimitivePart() Poly
- func (p Poly) Quo(d Poly) (Poly, error)
- func (p Poly) RationalRoots() []*big.Rat
- func (p Poly) Rem(d Poly) (Poly, error)
- func (p Poly) Resultant(q Poly) *big.Rat
- func (p Poly) Reverse() Poly
- func (p Poly) ScalarMul(r *big.Rat) Poly
- func (p Poly) Shift(a *big.Rat) Poly
- func (p Poly) SquareFreeFactorization() []SquareFreeFactor
- func (p Poly) SquareFreePart() Poly
- func (p Poly) String() string
- func (p Poly) Sub(q Poly) Poly
- type RatFunc
- func ConstRatFunc(r *big.Rat) RatFunc
- func DeterminantRatFunc(m [][]RatFunc) (RatFunc, error)
- func LogarithmicDerivativeIsRational(f RatFunc) (RatFunc, bool)
- func NewRatFunc(num, den Poly) (RatFunc, error)
- func OneRatFunc() RatFunc
- func RatFuncFromPoly(p Poly) RatFunc
- func ReduceToNormalForm(a2, a1, a0 Poly) (RatFunc, error)
- func VariationOfParameters(ys []RatFunc, g RatFunc) (RatFunc, error)
- func VariationOfParametersIntegrands(ys []RatFunc, g RatFunc) ([]RatFunc, error)
- func WronskianRatFunc(fs []RatFunc) (RatFunc, error)
- func XRatFunc() RatFunc
- func ZeroRatFunc() RatFunc
- func (f RatFunc) Add(g RatFunc) RatFunc
- func (f RatFunc) Den() Poly
- func (f RatFunc) Derivative() RatFunc
- func (f RatFunc) Div(g RatFunc) (RatFunc, error)
- func (f RatFunc) Equal(g RatFunc) bool
- func (f RatFunc) EvalComplex(z complex128) complex128
- func (f RatFunc) EvalFloat(x float64) float64
- func (f RatFunc) EvalRat(x *big.Rat) (*big.Rat, error)
- func (f RatFunc) Inv() (RatFunc, error)
- func (f RatFunc) IsPolynomial() bool
- func (f RatFunc) IsProper() bool
- func (f RatFunc) IsZero() bool
- func (f RatFunc) LogDerivative() (RatFunc, error)
- func (f RatFunc) Mul(g RatFunc) RatFunc
- func (f RatFunc) Neg() RatFunc
- func (f RatFunc) Num() Poly
- func (f RatFunc) PartialFractions() (Poly, []PartialFractionTerm)
- func (f RatFunc) PolynomialPart() (quotient Poly, remainder RatFunc)
- func (f RatFunc) Pow(n int) (RatFunc, error)
- func (f RatFunc) ScalarMul(r *big.Rat) RatFunc
- func (f RatFunc) String() string
- func (f RatFunc) Sub(g RatFunc) RatFunc
- type RationalIntegral
- type RecurrenceSolution
- type RecurrenceTerm
- type RecurrenceTermKind
- type RootCluster
- type SquareFreeFactor
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
LinearlyIndependentPoly reports whether the polynomials are linearly independent over Q, tested by a non-vanishing Wronskian.
func LinearlyIndependentRatFunc ¶
LinearlyIndependentRatFunc reports whether the rational functions are linearly independent over the constants, tested by a non-vanishing Wronskian.
func RatFromFloat ¶
RatFromFloat returns the exact rational value of the IEEE-754 float f. It returns nil if f is not finite.
func RatFromFrac ¶
RatFromFrac returns the rational number p/q. It panics only if q is zero, matching the behaviour of math/big.NewRat.
func RatFromString ¶
RatFromString parses a rational number written as "p/q", a decimal, or an integer. It reports whether parsing succeeded.
func RecurrenceValues ¶
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 ¶
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 ¶
WronskianMatrixPoly returns the Wronskian matrix of the polynomials ps.
func WronskianMatrixRatFunc ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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).
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 ¶
ConstOperator returns the zeroth-order operator that multiplies by the rational function a.
func IdentityOperator ¶
func IdentityOperator() Operator
IdentityOperator returns the identity operator (multiplication by 1).
func NewOperator ¶
NewOperator builds an operator from coefficients in ascending order of D (coeffs[0] is the zeroth-order term).
func OperatorFromPolys ¶
OperatorFromPolys builds an operator whose coefficients are the given polynomials, in ascending order of D.
func (Operator) Adjoint ¶
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) ApplyRatFunc ¶
ApplyRatFunc applies the operator to a rational function y, returning sum_i a_i y^(i).
func (Operator) IndicialPolynomial ¶
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) LeadingCoeff ¶
LeadingCoeff returns the coefficient of the highest-order term.
func (Operator) Order ¶
Order returns the order (highest power of D) of the operator; the zero operator has order -1.
func (Operator) SymbolPoly ¶
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 ¶
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 ConstPolyInt ¶
ConstPolyInt returns the constant polynomial equal to the integer n.
func DeterminantPoly ¶
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 NewPoly ¶
NewPoly builds a polynomial from coefficients given in ascending degree order (coeffs[0] is the constant term). The inputs are copied.
func PolyFromInts ¶
PolyFromInts builds a polynomial from integer coefficients in ascending degree order.
func RischExpIntegrate ¶
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 ¶
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 ¶
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 ¶
WronskianPoly returns the Wronskian determinant of the polynomials ps.
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) ConstantTerm ¶
ConstantTerm returns the coefficient of x^0.
func (Poly) Content ¶
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) Derivative ¶
Derivative returns the formal derivative dp/dx.
func (Poly) Discriminant ¶
Discriminant returns the discriminant of p, defined via the resultant of p and its derivative.
func (Poly) DivMod ¶
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) EvalComplex ¶
func (p Poly) EvalComplex(z complex128) complex128
EvalComplex evaluates p at the complex point z.
func (Poly) ExtendedGCD ¶
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 ¶
GCD returns the monic greatest common divisor of p and q. The GCD of two zero polynomials is zero.
func (Poly) IsConstant ¶
IsConstant reports whether p has degree at most zero.
func (Poly) LeadingCoeff ¶
LeadingCoeff returns the coefficient of the highest-degree term, or zero for the zero polynomial.
func (Poly) Monic ¶
Monic returns p scaled to be monic (leading coefficient 1). The zero polynomial is returned unchanged.
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) PrimitivePart ¶
PrimitivePart returns p divided by its content, so the result has integer coprime coefficients and positive leading sign preserved.
func (Poly) RationalRoots ¶
RationalRoots returns all distinct rational roots of p (without multiplicity) using the rational-root theorem. The zero polynomial yields nil.
func (Poly) Resultant ¶
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 ¶
Reverse returns the reversal x^deg * p(1/x), i.e. p with its coefficient list reversed.
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 ¶
SquareFreePart returns the square-free part of p, namely p / gcd(p, p').
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 ¶
ConstRatFunc returns the constant rational function equal to r.
func DeterminantRatFunc ¶
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 ¶
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 ¶
NewRatFunc builds the reduced rational function num/den. It returns ErrDivByZero when den is the zero polynomial.
func RatFuncFromPoly ¶
RatFuncFromPoly returns the rational function p/1.
func ReduceToNormalForm ¶
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 ¶
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 ¶
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 ¶
WronskianRatFunc returns the Wronskian determinant of the rational functions fs. An empty input returns ErrEmpty.
func (RatFunc) Derivative ¶
Derivative returns the derivative df/dx via the quotient rule.
func (RatFunc) EvalComplex ¶
func (f RatFunc) EvalComplex(z complex128) complex128
EvalComplex evaluates f at the complex point z.
func (RatFunc) EvalRat ¶
EvalRat evaluates f at the rational point x. It returns ErrDivByZero when the denominator vanishes there.
func (RatFunc) IsPolynomial ¶
IsPolynomial reports whether the denominator is a constant.
func (RatFunc) LogDerivative ¶
LogDerivative returns the logarithmic derivative f'/f. It returns ErrDivByZero when f is zero.
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 ¶
PolynomialPart returns the polynomial quotient and proper remainder so that f = quotient + remainder with the remainder proper.
func (RatFunc) Pow ¶
Pow raises f to the integer power n (n may be negative). A negative power of the zero function returns ErrDivByZero.
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 ¶
SquareFreeFactor is one factor of a square-free factorisation: the monic square-free polynomial Factor appears to the power Mult in the original.