1

I can calculate the root of a function using Newtons Method by subtracting the old x-value from the new one and checking for the convergence criterion. Is there a way of doing it when given a closed interval, e.g

Given a function and the interval [a,b] = [0.1, 3.0], the convergence criterion will be calculated by checking if [3.0 - 0.1] < 0.000001, i.e [b-a] < 0.000001.

The code I provided is calculating the convergence criterion using the x-values. I'm trying to figure out if there is a way I can use the interval instead of the x-values.

from math import *

x = 1.0 #initial value

for j in range(1, 101):
    xnew = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))

    if abs(xnew - x) < 0.000001:
        break
    x = xnew

print('Root = %0.6f ' % xnew)
print('Number of iterations = %d' % j)
Prog101
  • 109
  • 2
  • 10

1 Answers1

1

It sounds like you are wanting to guarantee that the root is found within a given interval (which is not something the Newton-Raphson can guarantee). You could use bisection for this. If you know the function changes sign in a given interval (and is continuous in the same) then something like the following works:

>>> from sympy.abc import x
>>> from sympy import nsolve
>>> ivl = 0,3
>>> expr = (x**2 + cos(x)**2 -4*x)
>>> nsolve(expr, x, ivl)
0.250324492526265

But it also looks like you might have some variables mixed up in what you are trying with the NR method. The xnew you are calculating looks very much like f(x)/f'(x) which is dx in xnew = x - dx. So if you write:

for j in range(1, 101):
  dx = (x**2 + cos(x)**2 -4*x)/(2*(x - cos(x)*sin(x) -2))
  if abs(dx) < 0.000001:
    break
  x = x - dx

print('Root = %0.6f ' % x)
print('Number of iterations = %d' % j)

you will get

Root = 0.250324 
Number of iterations = 4
smichr
  • 16,948
  • 2
  • 27
  • 34