Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from math import fabs
- e = 10e-3
- def newton_method(x0, f, df):
- x1 = x0 - f(x0) / df(x0)
- iteration = 1
- print('k | x(k) | F(x(k)) | dF(x(k)) | -F/dF')
- print('iter: {} | {} | {} | {} | '.format(iteration, x1, f(x1), df(x1), -f(x1)/df(x1)))
- while fabs(x1 - x0) >= e:
- iteration += 1
- x0 = x1
- x1 = x1 - f(x1) / df(x1)
- print('iter: {} | {} | {} | {} | '.format(iteration, x1, f(x1), df(x1), -f(x1)/df(x1)))
- return x1, iteration
- def main():
- intervals = [(-2, -1), (-1, 0), (0, 1)]
- def function(x): return x ** 3 + x ** 2 - x - 0.5
- def dfunction(x): return 3 * x ** 2 + 2 * x - 1
- # newton method
- print('Newton method')
- res, iterations = newton_method(intervals[0][0], function, dfunction)
- print('Root = {}, {} iterations'.format(res, iterations))
- res, iterations = newton_method(intervals[1][1], function, dfunction)
- print('Root = {}, {} iterations'.format(res, iterations))
- res, iterations = newton_method(intervals[2][1], function, dfunction)
- print('Root = {}, {} iterations'.format(res, iterations))
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement