2

I have a KDE which represent a probability density function (PDF). Now, I want to get the value of the variable lower that satisfies:

kde.integrate_box_1d(lower, 2.0) == 0.05

where 0.05 is the "critical value". 2.0 is the upper limit.

So far, I solve it using the follow code:

def finder(KDE, critical, lower, upper):
    stop = True
    search = lower
    while stop:
        if KDE.integrate_box_1d(search+0.00001,upper) > critical:
            search += 0.0001
        else: stop = False
    return search, KDE.integrate_box_1d(search,upper)

However, this code is inefficient and inaccurate. I wonder if you know a better way to find the correct value of lower

mgig
  • 2,395
  • 4
  • 21
  • 36
Ivan Castro
  • 581
  • 2
  • 10
  • 22

1 Answers1

1

this looks like 1d root finding to me. Have a look at

scipy.optimize

To be more specific, you could try something like

solver = scipy.optimize.brentq # or brenth or ridder or bisect
def finder(KDE, critical, lower, upper):
    def f(search):
        return KDE.integrate_box_1d(search, upper) - critical
    x, r = solver(f, lower, upper, full_output=True)
    assert r.converged
    return x

HTH, Paul

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Effectively. A close answer is found the book "Numerical Python: A Practical Techniques Approach for Industry" page 331 – Ivan Castro Jan 19 '17 at 01:21
  • @IvánCastro I'm afraid I don't have that book at hand. I've added some code to the answer. Could you please check whether it does what you want? – Paul Panzer Jan 19 '17 at 02:42