I have am coding the algorithm of Bolzano in Python. This is my code for now:
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
It works until it encounters cmp, which it doesn't recognise. However I don't see another way to do it, since Python doesn't have a sign function. Is there any other way to extract the sign of a number?
Is there any other way to extract the sign of a number?
How about writing your own?
Implementation
def sign(num):
return -1 if num < 0 else 1
Example
>>> sign(10)
1
>>> sign(-10)
-1
Ohh and cmp is a built-in that requires two parameters (numbers) and simply compares them and checks which of them is larger. You should have used it as follows
def Bolzano(fonction, a, b, tol=0.000001):
while abs(b-a)>tol:
m=(a+b)/2
if cmp(fonction(m), fonction(a)) == 0:
a=m
else:
b=m
return a, b