-
Notifications
You must be signed in to change notification settings - Fork 38
Closed
Description
The code
b=SpinBasis(40)
coherentspinstate(b,0.1,0.2)
throws OverflowError: binomial(80, 21) overflows
There is an easy solution to this. When dealing with potentially large numbers, it is better to operate their logarithms and exponentiate at the end. This should fix it:
using SpecialFunctions
logbinomial(N::Integer,n::Integer) = logfactorial(N) - logfactorial(n) - logfactorial(N-n)
function coherentspinstate(b::SpinBasis, theta::Real, phi::Real)
result = Ket(b)
data = result.data
N = length(b)-1
expphi = exp(0.5im*phi)
expphi_con = conj(expphi)
if theta==0 #prevents a log(0) below
data[1]=expphi_con^N
else
sinth = sin(0.5theta)
costh = cos(0.5theta)
logcosthexpphi_con=log(costh*expphi_con)
logsinthexpphi=log(sinth*expphi)
@inbounds for n=0:N
data[n+1] = exp(logbinomial(N, n)/2.0 + (N-n)*logcosthexpphi_con + logsinthexpphi*n)
end
end
return result
end
Metadata
Metadata
Assignees
Labels
No labels