Skip to content

Commit

Permalink
Expand Taylor series about nonzero points
Browse files Browse the repository at this point in the history
  • Loading branch information
hersle committed Oct 8, 2024
1 parent 75dd036 commit eeb1854
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/taylor.jl
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# TODO: around arbitrary point x = x0 ≠ 0
# TODO: error if x is not a "pure variable"
# TODO: optimize for multiple orders with loop/recursion
"""
taylor(f, x, n; rationalize=true)
taylor(f, x, [x0=0,] n; rationalize=true)
Calculate the `n`-th order term(s) in the Taylor series of the expression `f(x)` around `x = 0`.
Calculate the `n`-th order term(s) in the Taylor series of the expression `f(x)` around `x = x0`.
If `rationalize`, float coefficients are approximated as rational numbers (this can produce unexpected results for irrational numbers, for example).
Examples
Expand All @@ -19,6 +18,9 @@ julia> taylor(exp(x), x, 0:3)
julia> taylor(exp(x), x, 0:3; rationalize=false)
1.0 + x + 0.5(x^2) + 0.16666666666666666(x^3)
julia> taylor(√(x), x, 1, 0:3)
1 + (1//2)*(-1 + x) - (1//8)*((-1 + x)^2) + (1//16)*((-1 + x)^3)
```
"""
function taylor(f, x, n::Int; rationalize=true)
Expand All @@ -37,3 +39,15 @@ end
function taylor(f, x, n::AbstractArray{Int}; kwargs...)
return sum(taylor.(f, x, n; kwargs...))
end
function taylor(f, x, x0, n; kwargs...)
# 1) substitute dummy x′ = x - x0
name = Symbol(String(nameof(x)) * "") # e.g. Symbol("x′")
x′ = only(@variables $name)
f = substitute(f, x => x′ + x0)

# 2) expand f around x′ = 0
s = taylor(f, x′, n; kwargs...)

# 3) substitute back x = x′ + x0
return substitute(s, x′ => x - x0)
end
3 changes: 3 additions & 0 deletions test/taylor.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,6 @@ end
@test taylor(sinh(x), x, 0:7) - sum(1/factorial(2*n+1) * x^(2*n+1) for n in 0:3) == 0
@test taylor(cosh(x), x, 0:7) - sum(1/factorial(2*n) * x^(2*n) for n in 0:3) == 0
@test taylor(tanh(x), x, 0:7) - (x - x^3/3 + 2/15*x^5 - 17/315*x^7) == 0

# around x ≠ 0
@test substitute(taylor((x), x, 1, 0:6), x => x + 1) - taylor((1+x), x, 0:6) == 0

0 comments on commit eeb1854

Please sign in to comment.