0

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
    Hi, Welcome to Stack Overflow! :-) This seems like a maths question rather than a coding question. If you understand the maths and are struggling to convert that to code then can you post a little more about the maths that you're trying to turn into a python program? And if you don't understand the maths then this is off topic for SO, but you could ask over at [math.stackexchange](https://math.stackexchange.com/)! – Ari Cooper-Davis Nov 10 '19 at 01:47

1 Answers1

0

Sounds more like approximating roots by halving the interval. Here is an approach that I did with sympy to modularize it for different functions (though hopefully you will still find it useful):

def halving_the_interval(f_x, interval, i):

    v1 = f_x.evalf(subs={x : interval[0]})
    v2 = f_x.evalf(subs={x : interval[1]})

    # half of interval
    half = (interval[0] + interval[1]) / float(2)

    # f_(half)
    v3 = f_x.evalf(subs={x: half})

    if (abs(interval[1] - interval[0]) > 0.000001):
        # check intervals for where root lies
        # recursive step on new interval, update iterations
        if (v1 < 0 and v3 > 0):
            halving_the_interval(f_x, [interval[0],half], i+1)
        else:
            halving_the_interval(f_x, [half, interval[1]], i+1)
    else:
        print ("Root =  %0.6f " % half)
        print ("Number of iterations = %d" % i)

halving_the_interval(x**2 - 2, [1,2], 0)

And testing with function x^2 - 2 = 0 should find root at sqrt(2) ie. ~1.41.

$ halving_the_interval(x**2 - 2, [1,2], 0)

Root = 1.414214

Number of iterations = 20

Community
  • 1
  • 1
jackw11111
  • 1,457
  • 1
  • 17
  • 34