Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Barnsley Fern in Python

  • Last Updated : 22 Oct, 2018

Barnsley fern is a fractal shape created by mathematician Michael Barnsley. The geometric features of this fractal resemble a natural fern and hence it gets its name. Barnsley fern is created by iterating over a large number of times on four mathematical equations, introduced by Barnsley, known as Iterated Function System (IFS).

The transformation Barnsley used had the formula :

where, the letters had following value :

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

abcdefpPART
0000.16000.01Stem
0.850.04-0.040.8501.600.85Small Leaflet
0.20-0.260.230.2201.600.07Large Leaflet(Left)
-0.150.280.260.2400.440.07Large Leaflet(Right)

and “p” is the probability.



Thus the four equations are:
  f_1 :\\     x_{n+1} = 0\\     y_{n+1} = 0.16 y_n\\ \\ f_2 :\\     x_{n+1} = 0.85 x_n + 0.04 y_n\\     y_{n+1} = -0.04 x_n + 0.85 y_n + 1.6\\ \\ f_3 :\\     x_{n+1} = 0.2 x_n - 0.26 y_n\\     y_{n+1} = 0.23 x_n + 0.22 y_n + 1.6\\ \\ f_4 :\\     x_{n+1} = -0.15 x_n + 0.28 y_n\\     y_{n+1} = 0.26 x_n + 0.24 y_n + 0.44\\
With the help of above equations, the fern is created. Now lets see the Python3 implementation for the same.




# importing necessary modules
import matplotlib.pyplot as plt
from random import randint
  
# initializing the list
x = []
y = []
  
# setting first element to 0
x.append(0)
y.append(0)
  
current = 0
  
for i in range(1, 50000):
  
    # generates a random integer between 1 and 100
    z = randint(1, 100)
  
    # the x and y coordinates of the equations
    # are appended in the lists respectively.
      
    # for the probability 0.01
    if z == 1:
        x.append(0)
        y.append(0.16*(y[current]))
      
    # for the probability 0.85    
    if z>= 2 and z<= 86:
        x.append(0.85*(x[current]) + 0.04*(y[current]))
        y.append(-0.04*(x[current]) + 0.85*(y[current])+1.6)
      
    # for the probability 0.07    
    if z>= 87 and z<= 93:
        x.append(0.2*(x[current]) - 0.26*(y[current]))
        y.append(0.23*(x[current]) + 0.22*(y[current])+1.6)
      
    # for the probability 0.07    
    if z>= 94 and z<= 100:
        x.append(-0.15*(x[current]) + 0.28*(y[current]))
        y.append(0.26*(x[current]) + 0.24*(y[current])+0.44)
          
    current = current + 1
   
plt.scatter(x, y, s = 0.2, edgecolor ='green')
  
plt.show()        

Output :

Note: The whole output depends upon the coefficients of the equations. One experiment might be to change the coefficients and get a new pattern every time.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!