Skip to main content
Logo image

Section 31.3 Improving and Comparing the Algorithms

What happens if \(f'(x) = 0\) at some point during the iteration? Dividing by zero is never good news. Adjust your newton() function so that if \(f'(x) = 0\text{,}\) it stops the loop and returns \(0\) (failure); if it successfully finds the root, it should return \(1\) (success) instead. Test both cases in main().
Next, add the bisection function you wrote in the previous chapter into your rootfinding library as well— this time using a function pointer, exactly as newton() does, so both algorithms share the same style of interface.
Finally, let’s see which algorithm converges faster! Add an integer counter to both your newton() and bisection() functions that tracks how many times their while loop runs. In main(), run both methods to find the root of \(f(x) = x^3 - 8\text{,}\) and print the final root together with the number of iterations each method took.

admin.....open in new window

Which method converges faster— and by how much?