In: Computer Science
I'm writing a code for the Secant Method for root finding, but my code makes an infinite code of the correct answer. Below is my code, how do I fix it?
def f(x):
return (x**6)+7*(x**5)-15*(x**4)-70*(x**3)+75*(x**2)+175*x-125
def secant():
p0=float(input('Enter an initial guess for the root '))
p1=float(input('Enter another guess '))
TOL=float(input('Enter a tolerance in decimal form '))
n=15
i=1
while i<=n:
p=p1-f(p1)*(p1-p0)/(f(p1)-f(p0))
if abs(p-p1)<TOL:
print(p)
else:
p0=p1
p1=p
i=i+1
else:
print(p)
return p
print(secant())
So the program is mainly not running since you are not getting out of the loop when the tolerance condition is met .
Also the i=i+1 statement should be outside the if-else statements since everytime the tolerance condition is met the program is not going to the else statements and thus your i was not increasing , therefore you were getting a infinite loop.
also the second else statement was a syntax error
all these have been fixed below.
def f(x):
return (x**6)+7*(x**5)-15*(x**4)-70*(x**3)+75*(x**2)+175*x-125
def secant():
p0=float(input('Enter an initial guess for the root '))
p1=float(input('Enter another guess '))
TOL=float(input('Enter a tolerance in decimal form '))
n=15
i=1
while i<=n:
p=p1-(f(p1)*(p1-p0))/(f(p1)-f(p0))
i=i+1
if abs(p-p1)<TOL:
print(p)
break #added a break method
here so that the loop breaks when tolerance is met
else:
p0=p1
p1=p
print(p) #no need for another
else
return p
print(secant())