How to avoid Stack overflow

I have a program below which calculates Pi using Zeta(2) function, but it stack overflows when the limit is 260000

const limit=260000

@inline function formula(n::Int64)
    return 1.0/(Float64(n)*Float64(n))
end

function zetatwo(k::Int64)
    if k<limit
        return formula(k)+zetatwo(k+1)
    else
        return formula(k)
    end
end

println("Pi is ",sqrt(6.0*zetatwo(1)))

The output is

ERROR: LoadError: StackOverflowError:
Stacktrace:
 [1] zetatwo(::Int64) at /Users/ssiew/juliascript/zeta_two_Float64.jl:10 (repeats 99 times)
in expression starting at /Users/ssiew/juliascript/zeta_two_Float64.jl:16

It works when limit is 250000

const limit=250000

@inline function formula(n::Int64)
    return 1.0/(Float64(n)*Float64(n))
end

function zetatwo(k::Int64)
    if k<limit
        return formula(k)+zetatwo(k+1)
    else
        return formula(k)
    end
end

println("Pi is ",sqrt(6.0*zetatwo(1)))

The output is

Pi is 3.1415888338764764

How do I increase the stack to prevent the overflow?

Julia does not have tail call optimisation,
avoid deep recusion

@inline function formula(n::Int64)
    return 1.0/(Float64(n)*Float64(n))
end


calc_pi(limit) = sqrt(6.0*sum(formula, 1:limit))
println("Pi is ", calc_pi(1_000_000_000))
3 Likes

When calculating Zeta(2), you need to calculate the smallest value first.

@inline function formula(n::Int64)
    return 1.0/(Float64(n)*Float64(n))
end


calc_pi(limit) = sqrt(6.0*sum(formula, limit:-1:1))
println("Pi is ", calc_pi(1_000_000_000))