Skip to content

Commit 9f6cb5c

Browse files
heltonmcChris Geoga
andauthored
add power series
Co-authored-by: Chris Geoga <[email protected]>
1 parent aeddfe7 commit 9f6cb5c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/besselk.jl

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,3 +271,52 @@ function besselk_ratio_knu_knup1(v, x::T) where T
271271
xinv = inv(x)
272272
return xinv * (v + x + 1/2) + xinv * hn
273273
end
274+
275+
# originally contribued by @cgeoga https://github.com/cgeoga/BesselK.jl/blob/main/src/besk_ser.jl
276+
function _besselk_ser(v, x, maxit, tol, modify)
277+
T = promote_type(typeof(x), typeof(v))
278+
out = zero(T)
279+
oneT = one(T)
280+
twoT = oneT+oneT
281+
# precompute a handful of things:
282+
xd2 = x/twoT
283+
xd22 = xd2*xd2
284+
half = oneT/twoT
285+
if modify
286+
e2v = exp2(v)
287+
xd2_v = (x^(2*v))/e2v
288+
xd2_nv = e2v
289+
else
290+
lxd2 = log(xd2)
291+
xd2_v = exp(v*lxd2)
292+
xd2_nv = exp(-v*lxd2)
293+
end
294+
gam_v = gamma(v)
295+
gam_nv = gamma(-v)
296+
gam_1mv = -gam_nv*v # == gamma(one(T)-v)
297+
gam_1mnv = gam_v*v # == gamma(one(T)+v)
298+
xd2_pow = oneT
299+
fact_k = oneT
300+
floatk = convert(T, 0)
301+
(gpv, gmv) = (gam_1mnv, gam_1mv)
302+
# One final re-compression of a few things:
303+
_t1 = gam_v*xd2_nv*gam_1mv
304+
_t2 = gam_nv*xd2_v*gam_1mnv
305+
# now the loop using Oana's series expansion, with term function manually
306+
# inlined for max speed:
307+
for _j in 0:maxit
308+
t1 = half*xd2_pow
309+
tmp = _t1/(gmv*fact_k)
310+
tmp += _t2/(gpv*fact_k)
311+
term = t1*tmp
312+
out += term
313+
((abs(term) < tol) && _j>5) && return out
314+
# Use the trick that gamma(1+k+1+v) == gamma(1+k+v)*(1+k+v) to skip gamma calls:
315+
(gpv, gmv) = (gpv*(oneT+v+floatk), gmv*(oneT-v+floatk))
316+
xd2_pow *= xd22
317+
fact_k *= (floatk+1)
318+
floatk += 1.0
319+
end
320+
throw(error("$maxit iterations reached without achieving atol $tol."))
321+
end
322+

0 commit comments

Comments
 (0)