I am completely a beginner in programming, therefore please tell me if the answer to my question is very evident and obvious.
I started learning python a week ago, and having learnt the basics of using the Newton-Raphson method to solve equations, I came up with a piece of code that can give you atleat (only) 1 solution of a cubic equation. Here is the code I devised:-
def deg3(a,b,c,d,g):
y=a*g**3+b*g**2+c*g+d
return y
def solvedeg3equation():
e=float(input("e= ")) #for ax^3+bx^2+cx+d=0, with maximum error of e
a=float(input("a= "))
b=float(input("b= "))
c=float(input("c= "))
d=float(input("d= "))
count=1
g=0.01
while abs(deg3(a,b,c,d,g))>e and count<=100:
count=count+1
if 3*a*g**2+2*b*g+c==0:
g=g+0.001
g=g-deg3(a,b,c,d,g)/(3*a*g**2+2*b*g+c)
if count<=100:
print("The best guess is:",g)
print("iterations required: ",count)
else:
print("maximum iterations exceeded ")
print("iterations: ",count,"current guess: ",g)
One of the shortcoming of the Newton's method is that or f'(x)=0, it gives a math error and crashes. To overcome this, I used g=g+0.001, if the current value of g gives a zero derivative, where g is the current guess. Is there a better way to remove this problem, without using complex functions?
Another question I have is, can I include the provision of providing more than one root with minor changes to the code? One idea is to change the guess in such a way that now successive iterations bring about another root. But I do not know how to make such a guess, given one solution.