Skip to content

Instantly share code, notes, and snippets.

@jvlmdr
Created February 2, 2021 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvlmdr/5a2327c7ea5b14192bfd7f83c249daa3 to your computer and use it in GitHub Desktop.
Save jvlmdr/5a2327c7ea5b14192bfd7f83c249daa3 to your computer and use it in GitHub Desktop.
def farey(x, N):
    a, b = 0, 1
    c, d = 1, 1
    while b + d <= N:
        mediant = (a + c) / (b + d)
        if x == mediant:
            return a + c, b + d
        elif x > mediant:
            a, b = a + c, b + d
        else:
            c, d = a + c, b + d
    if c / d - x < x - a / b:
        return c, d
    else:
        return a, b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment