@Giovaneramos, your code has some problems:
1. As the staff has already mentioned, you need to update in f(x)
the multiplication to math.cosh(2*x)
2. When analyzing your code, I see that there is an architecture error, because when running with these values of a
and b
, when calculating the first x
, its value will be 0.5, but this value is already the root of the equation f(x)
, and as the output of the x
will be zero, which is always smaller than the erro
, and so you won’t even get into the while
, and therefore will not print anything (because the print
is inside the while
)
3. Using the print
end of his while
, by the concept you are using, the root being the average value within the range, so the root should be x
and not a
, how are you printing.
4. The approximate error would not be (b-a)
, but math.fabs(f(x))
Therefore, the simplest way to solve points 2 and 3 would be to exchange the print
into the if
, and not of while
, and thus ensure that it will always print the correct root, which in case is x
, 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")
right friend, solved this problem, now compiles but the paycharm goes crazy saying that there is no root in the equation, even with the correct interval, the program works with any polynomial of any degree
– Giovane Ramos
@Giovaneramos, you got the answer to your specific problem, presented in the question. The algorithm for calculating roots from bisections to be wrong is another problem, which I even believe already have a very elegant answer on the subject of a user named Victor Stafusa
– Jefferson Quesado
That’s the answer I mentioned
– Jefferson Quesado