[SciPy-user] Finding a point where a function becomes constant
Alan G Isaac
aisaac@american....
Tue Jul 17 08:46:17 CDT 2007
On Tue, 17 Jul 2007, Mathias Wagner apparently wrote:
> I have a numerical function defined f(x) that is zero for x < x_0 and f(x)>0
> for x > x_0. I have to find x_0.
> The problem with conventional root finding is that if the algorithm evaluates
> the function for any x < x_0 it will return this as a solution.
> Does anyone know whether there is some suitable algorithm for this problem or
> do I have to modify an existing method like bisection for my needs?
This one does not require any modification at all, I think.
(License: MIT.)
Cheers,
Alan Isaac
def bisect(f, x1, x2, eps=1e-8):
f1, f2 = f(x1), f(x2)
if f1*f2 > 0:
raise ValueError
#initialize xneg, xpos
xneg, xpos = (x1,x2) if(f2>0) else (x2,x1)
while xpos-xneg > eps:
xmid = (xneg+xpos)/2
if f(xmid) > 0:
xpos = xmid
else:
xneg = xmid
return (xneg+xpos)/2
More information about the SciPy-user
mailing list