Last active
June 29, 2019 00:35
-
-
Save notwa/30d84406190464faf5d23ba84817bcc9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def expect_cossim(n, approx=True): | |
""" | |
returns gamma(n / 2) / gamma((n + 1) / 2) / sqrt(pi) for positive integers. | |
""" | |
assert n > 0 | |
if approx: | |
# abs(error) < 1e-8 | |
if n >= 128000: | |
return np.reciprocal(np.sqrt(np.pi / 2 * n + 1)) | |
elif n >= 80: | |
poly = (2.4674010 * n - 2.4673232) * n + 1.2274046 | |
return np.reciprocal(np.sqrt(np.sqrt(poly))) | |
# fall-through when it's faster just to compute iteratively. | |
even = n % 2 == 0 | |
res = 2.0 if even else 1.0 | |
for i in range(2 if even else 1, n, 2): | |
res *= i / (i + 1) | |
return res / np.pi if even else res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment