Plotting a Bifurcation Diagram with different functions

292 views Asked by At

I'm working on plotting a bifurcation diagram for a couple different functions of x. My confusion lies in trying to use the numpy arrays and passing them to the conditionals in the sequence function. I can successfully use sequence(r, x) to plot a graph. The other bifurcation algorithm works just fine, but it does not use conditions in its sequence.

I have tried using numpy.vectorize(sequence) and numpy.where(...), but I also failed with those.

#numpy.where(...) attempt
def sequence(r, x):
   x1 = numpy.where(0 < x and x < 1/2, 0, 2 * r * x)
   x2 = numpy.where(1/2 < x and x < 1, 0, 2 * r * (1 - x)

   x = x1 + x2

   return x[x != 0]

And here is the rest:

def sequence(r, x):
    if 0 < x and x < 1/2:
        return 2 * r * x
    
    if 1/2 < x and x < 1:
        return 2 * r * (1 - x)

def plot_bifurcation2():
    n = 10000
    r = np.linspace(.4, .7, n)
    iterations = 1000
    last = 100

    x = 1e-6 * np.ones(n)
    lyapunov = np.zeros(n)

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize = (8, 9), sharex = True)

    for i in range(iterations):
        x = sequence(r, x)
        lyapunov += np.log(abs(r - 2 * r * x))

        if i >= (iterations - last):
            ax1.plot(r, x, ',k', alpha = .25)
        
    ax1.set_xlim(2.5, 4)
    ax1.set_title("Bifurcation diagram")

    ax2.axhline(0, color = 'k', lw = .5, alpha = .5)
    ax2.plot(r[lyapunov < 0], lyapunov[lyapunov < 0] / iterations, '.k', alpha = .5, ms = .5)
    ax2.plot(r[lyapunov >= 0], lyapunov[lyapunov >= 0] / iterations, '.k', alpha = .5, ms = .5)
    ax2.set_title("Lyapunov exponent")

    plt.tight_layout()
    plt.show()```
1

There are 1 answers

0
abyssmu On

What I needed was a bitwise and, & as opposed to logical and, and.

def sequence(r, x):
   x1 = numpy.where((0 < x) & (x < 1/2), 0, 2 * r * x)
   x2 = numpy.where((1/2 < x) and (x < 1), 0, 2 * r * (1 - x))

   x = x1 + x2

   return x[x != 0]