write a program that finds an approximate of the root in [-1,0], with an absolute error…
- User
write a program that finds an approximate of the root in [-1,0], with an absolute error less than 10^-4, checking the error after each iteration with the following equation: cos(2x) – ln(x2+1)=0
- Assistant
We can use the bisection method to find an approximate of the root in [-1,0] with an absolute error less than 10^-4.
First, we define a function to calculate the equation:
import math def f(x): return math.cos(2 * x) - math.log(x**2 + 1)Next, we implement the bisection method:
a = -1 b = 0 error = 1 while error > 10**-4: c = (a + b) / 2 if f(c) == 0: break elif f(a) * f(c) < 0: b = c else: a = c error = abs((b - a) / 2)The
aandbvariables represent the left and right bounds of the interval, which we have specified as [-1,0]. Theerrorvariable is initially set to 1, which is greater than our desired absolute error. We then enter awhileloop which continues until theerroris less than 10^-4.Within the loop, we calculate the midpoint
cof the interval using the equationc = (a + b) / 2. We then check iff(c) == 0which would mean we have found the root exactly and we can break out of the loop. Otherwise, we check if the product off(a)andf(c)is less than 0, which means the root is in the left subinterval [a,c], so we updateb = c. If the product off(a)andf(c)is greater than 0, the root is in the right subinterval [c,b], so we updatea = c. Finally, we calculate the absolute error as(b - a) / 2and update theerrorvariable.After the loop has finished, the variable
cwill contain an approximate of the root with an absolute error less than 10^-4. We can print this out:print(f'Approximate root: {c:.6f}')We have rounded the answer to 6 decimal places using Python's f-string formatting.