Skip to content

Instantly share code, notes, and snippets.

@refi64
Created July 27, 2020 01:48
Show Gist options
  • Save refi64/66f471d2f2aeef9a1bb807a7ecdb53ec to your computer and use it in GitHub Desktop.
Save refi64/66f471d2f2aeef9a1bb807a7ecdb53ec to your computer and use it in GitHub Desktop.
Stern-brocot tree search in K
/ square root of double precision epsilon (sqrt(2^-52))
E:1.4901161193847656e-8
/ abs[x]: absolute value of x
abs::$[x>0;x;-x]
/ xeq[x;y]: tests if x and y are approximately equal (difference is <sqrt(epsilon))
xeq::E>abs x-y
/ sb[q] Stern-brocot tree search, e.g. sbt[1%3] returns (1 3)
sbt:{[q]+/({[q;LH]~xeq[q;%/+/LH]}q;{[q;L;H]$[q>%/M:L+H;(M;H);(L;M)]}[q].)/:(0 1;1 0)}
/ benchmark:
/ \t sbt'i%|i:1+!10000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment