The Wayback Machine - https://web.archive.org/web/20240708112137/https://www.geeksforgeeks.org/fractal-trees-python/
Open In App

Fractal Trees in Python

Last Updated : 03 Oct, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Implementation of Fractal Binary Trees in python.

Introduction A fractal tree is known as a tree which can be created by recursively symmetrical branching.

The trunk of length 1 splits into two branches of length r, each making an angle q with the direction of the trunk. Both of these branches divides into two branches of length r*r, each making an angle q with the direction of its parent branch. Continuing in this way for infinitely many branching, the tree is the set of branches, together with their limit points, called branch tips.

So enough with the theory now let’s try to implementation in Python. To do so we require two python libraries pygame for GUI or graphical user interface and math which is a builtin library in python and will be used for mathematical tweakings.

To install pygame

pip install pygame

So how to proceed, its highly recommended that you know a bit about pygame and fractals.

First create a trunk and then start creating the branches for each trunk taking the size of the branches of the size equal to the 0.9*(length of the stem) and then again considering the branches as stem again and such repeating the process.




# Importing the python libraries
import pygame, math
  
# Initialize all imported pygame modules
pygame.init()
  
# Create a new surface and window.
surface_height, surface_width = 800, 600        #Surface variables
main_surface = pygame.display.set_mode((surface_height,surface_width))
  
# Captioning the window
pygame.display.set_caption("Fractal_Tree_geeksforgeeks")
  
def draw_tree(order, theta, sz, posn, heading, color=(0,0,0), depth=0):
  
   # The relative ratio of the trunk to the whole tree  
   trunk_ratio = 0.29     
  
   # Length of the trunk  
   trunk = sz * trunk_ratio
   delta_x = trunk * math.cos(heading)
   delta_y = trunk * math.sin(heading)
   (u, v) = posn
   newpos = (u + delta_x, v + delta_y)
   pygame.draw.line(main_surface, color, posn, newpos)
  
   if order > 0:   # Draw another layer of subtrees
  
      # These next six lines are a simple hack to make 
      # the two major halves of the recursion different 
      # colors. Fiddle here to change colors at other 
      # depths, or when depth is even, or odd, etc.
      if depth == 0:
          color1 = (255, 0, 0)
          color2 = (0, 0, 255)
      else:
          color1 = color
          color2 = color
  
      # make the recursive calls to draw the two subtrees
      newsz = sz*(1 - trunk_ratio)
      draw_tree(order-1, theta, newsz, newpos, heading-theta, color1, depth+1)
      draw_tree(order-1, theta, newsz, newpos, heading+theta, color2, depth+1)
  
  
def main():
    theta = 0
  
    while True:
  
        # Update the angle
        theta += 0.01
  
        # This little part lets us draw the stuffs 
        # in the screen everything
        main_surface.fill((255, 255, 0))
        draw_tree(9, theta, surface_height*0.9, (surface_width//2, surface_width-50), -math.pi/2)
        pygame.display.flip()
  
# Calling the main function
main()
pygame.quit()


Output:


          


Similar Reads

Mandelbrot Fractal Set visualization in Python
Fractal: A fractal is a curve or geometrical figure, each part of which has the same statistical character as the whole. They are useful in modeling structures (such as snowflakes) in which similar patterns recur at progressively smaller scales, and in describing partly random or chaotic phenomena such as crystal growth and galaxy formation. In sim
7 min read
Y Fractal tree in Python using Turtle
A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos. In this article, we will draw a colorful Y fractal
2 min read
Julia fractal in Python
Introduction to julia set In the context of complex dynamics, a topic of mathematics, the Julia set and the Fatou set are two complementary sets (Julia 'laces' and Fatou 'dusts') defined from a function. Informally, the Fatou set of the function consists of values with the property that all nearby values behave similarly under repeated iteration of
5 min read
Snowflakes Fractal using Python
To create Snowflake fractals using Python programmingWhat are fractals A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – th
3 min read
Fractal using Spirograph in Python
Introduction Spirograph toy that is used to produce complex patterns using plastic cogs and colored pens. A fractal is a curve, that is developed using a recurring pattern that repeats itself infinitely on a low scale. Fractals are used for modeling structures (such as snowflakes) or for describing partly chaotic phenomena. Spirograph can be used t
6 min read
Fractal Analytics Interview Experience
The description is of my interview experience with Fractal Analytics for the role of Imagineer (Trainee Data Scientist) during the campus placement drive in January 2021. Round 1(Aptitude Test): First-round had basic aptitude questions. The test had 70 questions in total divided into 4 sections - Data Analysis, Reasoning Ability, Quantitative Abili
3 min read
Fractal Analytics Interview Experience for Imagineer Role
Fractal Analytics is a purely an Artificial Intelligence-based company. You can check its website here www.fractal.ai. When Fractal visited my college, I searched on the Internet about how to crack Imagineer role (which is for freshers). But, there wasn't even a single article available for that. So, I decided to write an article about this role. T
1 min read
Fractal Analytics Interview Experience
I had interviewed for the Frontend Engineer (Grade 8) (Reactjs) role in January 2020 and here is my experience. I saw the job opening on the linkedin and applied for the same and after that contacted the recruiter who was my connection and told her that I would like to interview for it. She arranged the interview based on my CV. Here is my experien
2 min read
Fractal Analytics Interview Experience for Imagineer
Fractal Analytics is an AI-based company, and this is a fresher role. I had the following rounds during my campus placement: Online Test I: Data Analysis, Quantitative Ability, Reasoning, Verbal Online Test II: It had 8 questions in all. 4 were Python coding, 4 were SQL queries. All the questions were easy and do not have much weightage on the shor
2 min read
Fractal Analytics Interview Experience for Data Science
Fractal Analytics conducts an online test on DoSelect Platform. They have 13 questions. Out of these 13, 11 questions are MCQ-based and the rest 2 are coding-based data science questions.One of the questions that I recently found on the platform while giving the test was the wine quality prediction and evaluation question.You can find the demo code
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg