@GiovaneRamos, your code has some problems:
1. As the folks already mentioned, you need to update% with% multiplication to f(x)
2. When analyzing your code, I see that there is an architecture error, because when running with these values of math.cosh(2*x)
and a
, when calculating the first b
, its value will be 0.5, but this value already is the root of the equation x
, and since the output of the f(x)
function will be zero, which is always less than x
, and therefore will not even enter erro
, and therefore not will print nothing (since while
is within print
)
3. Using the while
end of your print
, for the concept you are using, the root is the average value within the range, so the root should be while
and not x
, as you are printing. Home
4. The approximate error would not be a
, but (b-a)
So the simplest way to solve points 2 and 3 is to change the math.fabs(f(x))
into print
, not if
, and thus ensure that it always prints the correct root , which in this case is while
, as below:
if f(a)*f(b) < 0:
x = (a + b)/2
while (math.fabs(f(x)) > erro):
x=(a+b)/2
if f(a)*f(x)<0:
b=x
g = (b - a)
else:
a=x
# Desconte a linha baixo caso queira acompanhar as iterações do algoritmo até chegar na raiz
# print("x: ", x, "erro: ", math.fabs(f(x)))
print("raiz: ", x , "valor da função: ", f(x), "erro aproximado", math.fabs(f(x)))
else:
print("não há raizes")