"""Rational logarithm and Perron-root certificates, with no floating decisions.""" from fractions import Fraction as Q from math import isqrt from .arithmetic import ceilq def _series(r,tol): t=(r-1)/(r+1) if not t: return Q(0),Q(0) power,total,j=t,Q(0),0 while True: total+=2*power/(2*j+1) j+=1;power*=t*t tail=2*power/((2*j+1)*(1-t*t)) if tail<=tol: return total,total+tail def log_bounds(x,tolerance=Q(1,10**12)): x,tolerance=Q(x),Q(tolerance) if x<=0 or tolerance<=0: raise ValueError("positive log argument and tolerance required") if x==1: return Q(0),Q(0) k=x.numerator.bit_length()-x.denominator.bit_length() scale=Q(1<=0 else Q(1,1<<(-k)) r=x/scale if r<1: k-=1;r*=2 elif r>=2: k+=1;r/=2 local=tolerance/(4*(abs(k)+1)) a,b=_series(r,local) c,d=_series(Q(2),local) if k>=0: lo,hi=a+k*c,b+k*d else: lo,hi=a+k*d,b+k*c bits=max(0,tolerance.denominator.bit_length()-tolerance.numerator.bit_length()+4) while Q(1,1<tolerance/8: bits+=1 scale=1< rho(A) iff (t I - A)x=1 has an everywhere positive solution. Exact rational bisection therefore works even for reducible/periodic A. """ a=tuple(tuple(map(Q,row)) for row in matrix) n=len(a) if not n or any(len(row)!=n or any(x<0 for x in row) for row in a): raise ValueError("nonempty square nonnegative matrix required") rows=tuple(map(sum,a)) if min(rows)<=0: raise ValueError("positive row sums required") tol=Q(relative_tolerance) if tol<=0: raise ValueError("positive relative tolerance required") lo,hi=max(min(rows),max(a[i][i] for i in range(n))),max(rows) steps=0 while hi-lo>tol*lo: if steps>=max_iterations: raise RuntimeError("spectral bisection budget exhausted; no certificate issued") t=(lo+hi)/2 shifted=[[(t if i==j else 0)-a[i][j] for j in range(n)] for i in range(n)] x=solve(shifted,[1]*n) if x is not None and min(x)>0: hi=t else: lo=t steps+=1 return {"lower":lo,"upper":hi,"iterations":steps, "method":"exact rational positive-resolvent bisection"} def matmul(a,b): return [[sum((a[i][k]*b[k][j] for k in range(len(b))),Q(0)) for j in range(len(b[0]))] for i in range(len(a))] def serializable(x): if isinstance(x,Q): return str(x) if isinstance(x,dict): return {str(k):serializable(v) for k,v in x.items()} if isinstance(x,(list,tuple)): return [serializable(v) for v in x] return x