Skip to content

Instantly share code, notes, and snippets.

@dmishin
Created March 26, 2025 23:51
Show Gist options
  • Select an option

  • Save dmishin/40f44bf58c018f7a8df1b8735efefbfa to your computer and use it in GitHub Desktop.

Select an option

Save dmishin/40f44bf58c018f7a8df1b8735efefbfa to your computer and use it in GitHub Desktop.
Calculate the simplest rational number between log_2(3) and log_2(3)-1/2^{70}
import mpmath
from typing import Tuple
def simplest_rational_in_range(a:mpmath.mpf, b:mpmath.mpf)->Tuple[int,int]:
#take integer part of both numbers
d1 = int(mpmath.floor(a))
d2 = int(mpmath.floor(b))
if d1 != d2:
assert d1 < d2
return d1+1, 1
#take fractional part of both numbers
p,q = simplest_rational_in_range(1/mpmath.frac(b), 1/mpmath.frac(a))
return q+d1*p, p
#sanity check
assert simplest_rational_in_range(3/17 - 1e-10, 3/17 + 1e-10) == (3,17)
N = 70
mpmath.mp.prec = 2*N
#Take at least 2N bits of precision
a = mpmath.log(3, 2)
eps = mpmath.mpf(1)/2**N
b = a+eps
p,q = simplest_rational_in_range(a, b)
print(f"{p}/{q}")
print(p+q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment