Advertisement
here2share

# Tk_Newton_Raphson_Fractal.py

May 13th, 2022
849
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Tk_Newton_Raphson_Fractal.py
  2.  
  3. from tkinter import *
  4. from PIL import Image, ImageTk
  5. from itertools import combinations
  6. from cmath import *
  7.  
  8. ww = 600
  9. hh = 600
  10.  
  11. # creates a z**4+1 = 0 fractal using the Newton-Raphson
  12. # root finding method
  13. delta       = 0.000001  # convergence criteria
  14. iters       = 30        # number of iterations
  15.  
  16. # these are the solutions to the equation z**4+1 = 0 (Euler's formula)
  17. solutions = [cos((2*n+1)*pi/4)+1j*sin((2*n+1)*pi/5) for n in range(4)]
  18. colors = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0)]
  19.  
  20. def draw():
  21.     image.putdata(rgb)
  22.     photo = ImageTk.PhotoImage(image)
  23.     canvas.create_image(0,0,image=photo,anchor=NW)
  24.     canvas.update()
  25.    
  26.  
  27. root = Tk()
  28. root.title("Tk_")
  29. root.geometry("%dx%d+0+0"%(ww,hh))
  30.    
  31. canvas = Canvas(root, width=ww, height=hh)
  32. canvas.pack()
  33.  
  34. image = Image.new("RGB", (ww,hh), (255,255,255))
  35.  
  36. rgb = []
  37. for re in range(0, ww):
  38.     for im in range(0, hh):
  39.         z = (re+1j*im)/hh
  40.         for i in range(iters):
  41.             try:
  42.                 z -= (z**4+1)/(4*z**3)
  43.             except ZeroDivisionError:
  44.                 continue
  45.             if(abs(z**4+1)<delta):
  46.                 break
  47.  
  48.         # color depth is a function of the number of iterations
  49.         color_depth = int((iters-i)*255.0/iters)
  50.  
  51.         # find to which solution this guess converged to
  52.         err = [ abs(z-root) for root in solutions ]
  53.         distances = zip(err, range(len(colors)))
  54.  
  55.         # select the color associated with the solution
  56.         color = [i*color_depth for i in colors[min(distances)[1]]]
  57.         rgb.append(tuple(color))
  58. draw()
  59.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement