One Byte Wealth

Wednesday, October 26, 2005

Regular Polygon

When all edges of polygon are having same lengths and meeting at same interior angle, that is being known as regular polygon. Radius and number of vertices(edges) are the known factors based on which the polygon is constrcuted.

First interior angle is calculated by:
angle = 2*math.pi/vertices

Now allocate each point by formula

>>> for i in range(0,vertices):
. . . X = math.cos(angle*i)*radius
. . . Y = math.sin(angle*i)*radius

Following image shows the simple polygon drawn on my screen



By adding code for GUI and lines between the allocated points of polygon, final program will be as following,

from Tkinter import *
import math

# Known Polygon Params
# Outer dia, Center point and vertices
OuterDia = 200
Cpx = 200
Cpy = 150
vertices = 6

# First point
fromX = Cpx + OuterDia/2
fromY = Cpy

# Calculate angle between edges
angle = 2*math.pi/vertices

root = Tk()
root.title("Polygon")
canvas = Canvas(width=400,height=300,background =‘white‘)

# Core logic goes here
# I made changes to draw lines
# rather than finding points

for i in range(0,vertices+1):
toX = math.cos(angle*i)*OuterDia/2 + Cpx
toY = math.sin(angle*i)*OuterDia/2 + Cpy
canvas.create_line(toX,toY,fromX,fromY,fill=‘brown‘)
fromX = toX
fromY = toY
canvas.pack()
mainloop()

Labels: ,

Sunday, October 23, 2005

Simple Sine

Implementing sine function, is the very primary and simple assignment.Here I used Tkinter interface for GUI, cause it takes very few lines to demonstrate/show the requirements.I used math library and small lines are drawn to form curve.




Complete code will be like this,




from Tkinter import *
import math
PrevX = 0
PrevY = 150


## Created a small segment of 1.0 length

def point(x,y):
return(x-0.5,y-0.5,x+0.5,y+0.5)

## Create Canvas Window and draw base line markups

root = Tk()
root.title("SinWave")
canvas = Canvas(width=400,height=300,bg='white')
canvas.create_line(0,150,400,150,fill='red')
canvas.create_text(10,160,text='0')
canvas.create_text(100,160,text='90')
canvas.create_text(200,160,text='180')
canvas.create_text(300,160,text='270')
canvas.create_text(30,290,text='SinWave')


## Implement core logic

for i in range(0,1000):
x = ((i*400)/100)
y = -(math.sin(math.pi*2*i/100)*100)+152
canvas.create_line(PrevX,PrevY,x,y,fill='blue')
PrevX=x
PrevY=y

canvas.pack()
mainloop()



following is just more interesting ..





Here is another for loop with some changes, X multiplication factor is decreased and combined result is two sine waves, code will be something like this,




for i in range(0,1000):
x = (i*400)/100
y = (math.sin(math.pi*2*i/100)*100)+148
canvas.create_line(PrevX,PrevY,x,y,fill='green')
PrevX=x
PrevY=y

PrevX = 0
PrevY = 150
for i in range(0,1000):
x = (i*200)/100
y = (math.sin(math.pi*2*i/100)*50)+148
canvas.create_line(PrevX,PrevY,x,y,fill='green')
PrevX=x
PrevY=y

Labels: ,