Skip to content

Binomial overflow when constructing spin coherent state with large S #43

@saulpila

Description

@saulpila

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions