Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot Mandelbrot with matplotlib / pyplot / numpy / python

I am new to python and learning by following Python "Scientific lecture notes Release 2013.1" tutorial. Please help me solve this Mandelbrot problem in the srcreenshot below (Pg 71). Please provide step-wise commands with explanation if possible because programming concepts are new to me.

http://dl.dropbox.com/u/50511173/mandelbrot.png

I tried to solve this as follows:

import numpy as np
import matplotlib.pyplot as plt

x,y=np.ogrid[-2:1:10j,-1.5:1.5:10j]
c=x + 1j*y
z=0
for g in range(50):
  z=z**2 + c

plt.imshow(z.T, extent=[-2,1,-1.5,1.5])

I encountered the following error "TypeError: Image data can not convert to float"

What does this error exactly mean and how to correct it? I am finding it difficult to understand the imshow() function. What do the individual terms inside imshow() mean?

Thank You.

like image 419
nilesh Avatar asked Feb 22 '13 12:02

nilesh


People also ask

How do you plot a Mandelbrot set in Python?

Plot of the Mandelbrot SetConvert the coordinate of the pixel into a complex number of the complex plane. Call the function mandelbrot. If mandelbrot returns MAX_ITER , plot a black pixel, otherwise plot a pixel in a color that depends on the number of iterations returned by mandelbrot.

What is the use of matplotlib Pyplot plot () function?

plot() Function. The plot() function in pyplot module of matplotlib library is used to make a 2D hexagonal binning plot of points x, y.

How do you make a Mandelbrot set?

Remember that the formula for the Mandelbrot Set is Z^2+C. To calculate it, we start off with Z as 0 and we put our starting location into C. Then you take the result of the formula and put it in as Z and the original location as C. This is called an iteration.

Can you use matplotlib in Python?

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Matplotlib makes easy things easy and hard things possible. Create publication quality plots.


1 Answers

The Mandelbrot set is not the values of z you are trying to plot, which are giving you problems because they are complex numbers. The Mandelbrot set is made up of the points p of the complex plane for which the recurrence relation z_n = z_n-1**2 + p remains bounded. This is checked in a practical way by comparing the result after a few iterations to some threshold. In your case, if you add the following lines after your for loop:

threshold = 2
mask = np.abs(z) < threshold

and then plot mask you should see the set plot on screen.

To understand the general workings of imshow's arguments, you will be better off reading the docs than asking here.

like image 181
Jaime Avatar answered Oct 05 '22 12:10

Jaime