Question

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.

Was it helpful?

Solution

Make a second procedure for the derivative. Even better, make a class for the numerical functions holding the coefficients obtained during initialization and providing methods for value and derivative.

Use x/(eps^2+x^2) to desingularize the function 1/x. Practically, this should play no role since convergence to multiple roots is slow so in more advanced implementations you have to implement code to detect this and speed it up.

To get the other roots, use the Horner-Ruffini scheme to compute the deflated quadratic polynomial and solve this using the solution formula.

And try to avoid computing the same value multiple times. This is not important here, but for more expensive functions this becomes critical.

OTHER TIPS

I've made the program using C to calculate the roots of any user entered polynomial in in a given interval. This is the link to the code

Newton's method program (in C) loop running infinitely

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top