Dilshod Davronov Dilshod Davronov - 1 year ago 98
Python Question

complex math exercise on python

this is the task I get:
Complex numbers can be represented on a two-dimensional space. Consider complex numbers cc of the form c=x+1j*y (j is the imaginary unit), where x∈[−2,0.5] and y∈[−1,1]. Imagine to have a two-dimensional grid in this space, with each step of the grid being 10ˆ(-2) . For each c corresponding to one of the nodes of the grid, calculate the iterative function

Z_{n+1} = Zˆ2_n + c
, with n∈[1,100] and Z_0=0 . Plot the grid by coloring with black the cell corresponding to c if Z_n diverges (i.e. |Z_n| is a NaN, otherwise color it with white.

Since I am not a math student, I am in trouble with that. So far, I could do till this point:

import numpy as np

x_values = np.arange(-2, 0.5, 0.01)
y_values = np.arange(-1, 1, 0.01)
M = np.zeros((len(x_values), (len(y_values))), dtype = "complex")

for x in range(len(x_values)):
for y in range(len(y_values)):
M[x][y] = x_values[x] +1j*y_values[y]

could you tell me how I can define a function that takes a grid/array like the one we have, initializes z=0 and then 100 times (i.e. for n in range(100)) does: z = z**2 + grid
then after the loop return z.
then to plot the image:

Answer Source

You were almost there!

Just add a little bit more to your for-loops:

for x in range(len(x_values)): 
    for y in range(len(y_values)): 
        for i in range(100):
            M[x][y] = M[x][y]**2 + (x_values[x] + 1j*y_values[y])

(I don't have numpy available at the moment, so I couldn't test it, but it's not too complicated so it's probably fine.)

As for the plotting, I suggest checking out matplotlib. If you have trouble, ask another SO question. But until you've tried something, I don't want to just write the whole thing for you. ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download