Skip to content

Instantly share code, notes, and snippets.

@syrte
Last active July 6, 2016 08:50
Show Gist options
  • Save syrte/74a0409e206555388e88c0f5d88159ac to your computer and use it in GitHub Desktop.
Save syrte/74a0409e206555388e88c0f5d88159ac to your computer and use it in GitHub Desktop.
def findroot(y0, x, y):
"""
y0: scalar
x: 1D array
y: function or 1D array
"""
import numpy as np
x = np.asarray(x)
assert x.ndim == 1
if callable(y):
y = y(x)
y = np.asarray(y)
assert x.shape == y.shape
ix1 = np.diff(y - y0 >= 0).nonzero()[0]
ix2 = ix1 + 1
x1, x2 = x[ix1], x[ix2]
y1, y2 = y[ix1], y[ix2]
x0 = (y0 - y1) / (y2 - y1) * (x2 - x1) + x1
return x0
@syrte
Copy link
Author

syrte commented Jul 5, 2016

Example

from scipy.stats import norm
func = norm.pdf
x = linspace(-3, 3, 21)
print func(findroot(0.3, x, func(x)))
print func(findroot(0.2, x, func(x)))
print func(findroot(0.2, x, func))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment