Search code examples
pythonnewtons-method

Newton's Basins of Attraction


I am trying to plot the Newton's Basins of Attraction for the polynomial z^3-1 using python. I am using Newton-Raphson Iterative method to plot the graph.

Till now, I am able to plot this: Newton Basin My Plot

What I want to generate is something like this: Required Plot

Could someone please suggest how can I do it?


Update 1

After including the initial points (which I had mistakenly omitted): Improved Plot


Update 2

Here is the code for the Newton-Raphson loop. Is there any error in the code that causes the slow operation?

def newtonraphson(z):
    if z == 0:
        return False
    z1 = 0
    z2 = z
    tolerance = 1.0e-12

    while True:
        z1 = z2
        z2 = z1 - function(z1)/derivative(z1)
        if abs((z2 - z1).a) < tolerance:
            break

    return z2

Solution

  • The plot you're getting looks "about right," except that it's lacking more points and them being evenly distributed.

    How are you choosing which points to plot and which not to?

    In general, you'll want to solve your equation your whole range of xs and ys as initial conditions. To select all those initial xs and ys, you want a small-enough step for your graph to look pretty (but not small enough that you're wasting time calculating points that end up being part of the same pixel).

    Then you'll want to iterate the Newton-Raphson method not for a fixed number of steps, but rather until your solution is close enough to z^3-1 == 0 (equivalently, until z^3-1 is small enough). This way you're sure to get a color for each point.

    EDIT to answer your comment:

    when I try to sample more points, the CPU usage reaches 100% and my computer starts lagging and sometimes hangs

    You need to give control back to the UI thread every once in a while. This will make your plot slower, but it will ensure that it is responsive. Ideally, you would perform all calculations in a background thread, and only communicate with your UI thread for it to plot each pixel.