Reputation: 77
I want to put this into a function newton(x) that allows users to enter there value for x.
from math import *
x=20
for iteration in range(1, 1001):
xnew = x - (((3*10**-5)*exp((log1p(10**3/(3*10**-5)))*(1-exp(-.12*x))))-1)/(.12*(3*10**-5)*exp((log1p(10**3/(3*10**-5))))*(1-exp(-.12*x)*(-.12*x))) # the Newton-Raphson's formula
print("Error",x-xnew," Xn: ", xnew)
if abs(xnew - x) < 0.000001:
break
x = xnew
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)
Upvotes: 1
Views: 46
Reputation: 106588
You can make it a function that returns a 2-tuple:
from math import *
def newton(x):
xnew = iteration = None
for iteration in range(1, 1001):
xnew = x - (((3*10**-5)*exp((log1p(10**3/(3*10**-5)))*(1-exp(-.12*x))))-1)/(.12*(3*10**-5)*exp((log1p(10**3/(3*10**-5))))*(1-exp(-.12*x)*(-.12*x))) # the Newton-Raphson's formula
print("Error",x-xnew," Xn: ", xnew)
if abs(xnew - x) < 0.000001:
break
x = xnew
return xnew, iteration
xnew, iteration = newton(20)
print('The root : %0.5f' % xnew)
print('The number of iterations : %d' % iteration)
Upvotes: 2