import sys, numpy as np
Lam = np.sqrt(7*1.2020569031595942)
def make(M):
    idx = np.arange(-M, M+1); N = len(idx)
    K = (idx[None,:] - idx[:,None]).astype(float)   # k = j - i
    np.fill_diagonal(K, 1.0)
    sg = np.sign(idx[None,:] - idx[:,None]).astype(float)
    KR = (M + 1 - idx).astype(float)   # first frozen site to the right, k>0
    KL = (M + 1 + idx).astype(float)   # first frozen site to the left, |k|
    def tail(K0, d):
        # sum_{k>=K0} [(k+d)^-2 - k^-2], Euler-Maclaurin, cancellation-free
        I = -d/(K0*(K0+d))
        f = -d*(2*K0+d)/(K0**2*(K0+d)**2)
        fp = 2*d*(3*K0**2+3*K0*d+d**2)/(K0**3*(K0+d)**3)
        return I + f/2 - fp/12
    def F(u):
        Dm = u[None,:] - u[:,None]
        T = -Dm*(2*K+Dm)/(K**2*(K+Dm)**2)   # (k+d)^-2 - k^-2, stable; valid for k<0 too
        acc = (sg*T).sum(axis=1)
        # frozen tails (u=0): right d=-u_i ; left: distance k - d with d=-u_i -> k+u_i
        acc += tail(KR, -u) - tail(KL, u)
        return acc
    return idx, F
A=[[],[1/5],[3/40,9/40],[44/45,-56/15,32/9],[19372/6561,-25360/2187,64448/6561,-212/729],
[9017/3168,-355/33,46732/5247,49/176,-5103/18656],[35/384,0,500/1113,125/192,-2187/6784,11/84]]
Cn=[0,1/5,3/10,4/5,8/9,1,1]
B5=np.array([35/384,0,500/1113,125/192,-2187/6784,11/84,0])
B4=np.array([5179/57600,0,7571/16695,393/640,-92097/339200,187/2100,1/40])
def run(eps, M, rtol=1e-11, gstop=1e-6):
    idx, F = make(M); N = len(idx)
    y = np.zeros(2*N); y[M] = eps
    def rhs(y): return np.concatenate([y[N:], F(y[:N])])
    t=0.0; h=1e-2; n=0; k1=rhs(y)
    while True:
        ks=[k1]
        for s_ in range(1,7):
            ks.append(rhs(y+h*sum(a*k for a,k in zip(A[s_],ks) if a!=0)))
        Kk=np.array(ks)
        ynew=y+h*(B5@Kk); err=h*((B5-B4)@Kk)
        gn=1+np.diff(ynew[:N])
        if gn.min()<=0 or not np.all(np.isfinite(ynew)):
            h*=0.3; continue
        # scale: displacement magnitude (global) so the tolerance is relative to the disturbance size
        sc=rtol*max(np.abs(ynew).max(), eps)
        e=np.abs(err).max()/sc
        if e<=1:
            t+=h; y=ynew; k1=ks[6]; n+=1
            if gn.min()<gstop: break
        h*=min(3.0,max(0.2,0.9*e**-0.2)) if e>0 else 3.0
    u=y[:N]; g=1+np.diff(u); j=int(np.argmin(g))
    T=t+g[j]**1.5/3
    return T,(int(idx[j]),int(idx[j+1])),np.sort(g)[1],0,n
if __name__ == '__main__':
    M = int(sys.argv[1]); exps = [float(a) for a in sys.argv[2:]]
    for e in exps:
        eps = 10.0**(-e)
        T, pair, g2, st, n = run(eps, M)
        L = np.log(1/eps); LL = np.log(L)
        print(f"eps=1e-{e:g} M={M} T={T:.8f} pair={pair} 2nd-min-gap={g2:.3f} d1={T-L/Lam:.5f} d2={T-(L+0.5*LL)/Lam:.5f} st={st} steps={n}", flush=True)
