Python Intro #02 | Function – Random Walk

Contents

  1. Random Walk
    1. Initial Setup
    2. Loop
  2. Function
    1. Concept
    2. Declaration/ Arguments / Return
    3. Usage
  3. Practice – Multiple Random Walks
    1. Random walk with function
    2. Initial Setup
    3. Loop

Random Walk

Initial Setup

import rhinoscriptsyntax as rs
import random
import math

points = []
point = rs.AddPoint(0,0,0)
points.append(point)

Loop

for i in range(x):
    theta = (random.random()-0.5)*math.pi*2

    point = rs.CopyObject(point)
    rs.MoveObject(point,[math.cos(theta)*y,math.sin(theta)*y,0])
    points.append(point)

Function

Concept

Function is the advanced feature in programming and is useful to make scripts more smart. Function is similar to the function in mathematics, it needs a couple of arguments (0 argument is also possible), and return several values as result.

Function is something like components in Grasshopper. They have some inputs and outputs. Arguments are inputs and Returns are output.

Declaration / Arguments / Return

The syntax to define functions is following:

def <function name>(<arguments>):
 ...
 return <value to return>

Following is the simplest example of function:

def addition(s,t):
 f = s+t
 return f

Usage

Using function is very easy. Following is a example to use previous function:

def addition(s,t):
 return s+t

a = addition(x,y)

Practice – Multiple Random Walks

Random Walk with Function

import rhinoscriptsyntax as rs
import random
import math

points = []
point = rs.AddPoint(0,0,0)
points.append(point)

def moveRandom(pt, range):
    theta = (random.random()-0.5)*math.pi*2

    returnPt = rs.CopyObject(pt)
    rs.MoveObject(returnPt,[math.cos(theta)*y,math.sin(theta)*y,0])

    return returnPt

for i in range(x):
    newPt = moveRandom(point, y)

    point = newPt
    points.append(newPt)

a=rs.AddPolyline(points)

 Multiple Random Walk

import rhinoscriptsyntax as rs
import random
import math

def moveRandom(pt, range):
    theta = (random.random()-0.5)*math.pi*2
    
    returnPt = rs.CopyObject(pt)
    rs.MoveObject(returnPt,[math.cos(theta)*y,math.sin(theta)*y,0])
    
    return returnPt

listOfPoints = []

for j in range(10):
    
    points = []
    point = rs.AddPoint(0,0,0)
    points.append(point)
    
    for i in range(x):
        newPt = moveRandom(point, y)
        
        point = newPt
        points.append(newPt)
    
    listOfPoints.append(points)

listOfPolylines = []

for j in range(10):
    pl = rs.AddPolyline(listOfPoints[j])
    listOfPolylines.append(pl)

a = listOfPoints