Skip to content

Instantly share code, notes, and snippets.

@bryanyang0528
Created September 1, 2017 03:05
Show Gist options
  • Save bryanyang0528/4befdd146670960adbfcfb04185cc8e9 to your computer and use it in GitHub Desktop.
Save bryanyang0528/4befdd146670960adbfcfb04185cc8e9 to your computer and use it in GitHub Desktop.
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.00001):
"""find approximate inverse using binary search"""
# if not standard, compute standard and rescale
if mu != 0 or sigma != 1:
return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance)
low_z, low_p = -10.0, 0 # normal_cdf(-10) is (very close to) 0
hi_z, hi_p = 10.0, 1 # normal_cdf(10) is (very close to) 1
while hi_z - low_z > tolerance:
mid_z = (low_z + hi_z) / 2 # consider the midpoint
mid_p = normal_cdf(mid_z) # and the cdf's value there
if mid_p < p:
# midpoint is still too low, search above it
low_z, low_p = mid_z, mid_p
elif mid_p > p:
# midpoint is still too high, search below it
hi_z, hi_p = mid_z, mid_p
else:
break
return mid_z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment