Reputation: 455
I am trying to code the bissection method on python, and I am having trouble applying it to different functions. So far I have this code:
def Bolzano(fonction, a, b, tol=0.000001):
while abs(b-a)>tol:
m=(a+b)/2
if cmp(fonction(m))==cmp(fonction(a)):
a=m
else:
b=m
return a, b
This code doesn't work well because I don't know how to define the function. Writing simply
Bolzano(3*x,0.5,1.0)
does not work because x is not defined. Because of this, I can't check if anything is wrong with the rest of the code.
Of course I could first define the function and then just apply it, but I want to be able to change the functions whils always keeping the same algorithm without rewriting it. Any help?
Upvotes: 0
Views: 1356
Reputation: 43497
You could use lambdas:
Bolzano(lambda x: 3*x,0.5,1.0)
Or define a function that you pass to Bolzano
:
def f(x):
return 3*x
Bolzano(f, 0.5, 1.0)
Then you can just keep adding functions:
def f(x):
return 3*x
def f1(x):
return 3*x+6
Bolzano(f, 0.5, 1.0)
Bolzano(f1, 0.5, 1.0)
Upvotes: 2