Using bisection method to find p3 for f(x) = sqrt(x) - cos(x), I got the right answer on paper p3 = .625
I am having a trouble converting the problem and solving it using Jupyter notebook. Any tips?
CodePudding user response:
0.625 is the third guess in the approximation process so the for loop should be completed before the fourth iteration and the code should be as follows.
import math
##problem statement
#finding a root of f(x) = sqrt(x)-cos(x) between the interval [0,1]
#f(0) = -1 f(1) = 0.45969.. so there is at least one root between the interval [0,1]
a = 0
b = 1
maxIt = 100
negative_result = math.sqrt(a) - math.cos(a)
positive_result = math.sqrt(b) - math.cos(b)
for i in range(maxIt):
if i == 3:
print("answer is: ", guess)
break
guess = (a b)/2
guess_result = math.sqrt(guess) - math.cos(guess)
if guess_result*negative_result >= 0:
a = guess
else:
b = guess
And the output is
0.625
