Using the Equation of a Straight Line in Python
The equation of a straight line has the general form
y = mx + c;
where m is the slope and c
is the intercept on the y-axis.
For a vertical line, x is constant and for
a horizontal line, y is constant.
Generating Straight Lines for Python
Given any 2 points (x1, y1)
and (x2, y2); we'll have:
|
y2 - y1 |
= |
y - y1 |
x2 - x1 |
x - x1 |
⇒ y = ( |
y2 - y1 |
) x + |
x2y1 - x1y2 |
x2 - x1 |
x2 - x1 |
Comparing this to the general equation of a straight line,
i.e. y = mx + c
m = |
y2 - y1 |
x2 - x1 |
& |
c = |
x2y1 - x1y2 |
x2 - x1 |
Say we are to find the equation for the line represented
by the arbitrary points (50, 50) and (200, 100):
m = |
100 - 50 |
= |
50 |
= |
1 |
200 - 50 |
150 |
3 |
& |
c = |
200(50) - 50(100) |
= |
10000 - 5000 |
200 - 50 |
150 |
= |
5000 |
= |
100 |
150 |
3 |
Hence,
y = 1/3x + 100/3
or
3y = x + 100
Code to Animate a Graphic Object by a Line Equation in Python
To make a graphic (dot) travel by the equation of a line;
continuously increment x, and use the equation to
get the corresponding y value.
Let's do so with the above equation representing points
(x1, y1) = (50, 50)
and (x2, y2) = (100, 200).
Create a new File; File, New File.
Call it StraightLine.py.
Type out the adjoining Python / Turtle code for animating an image
body through the path of a straight line.
Python code for StraightLine class
from Facet import Template
def prep():
global x1, y1, x_dot, y_dot, m, c, restart
restart = False
scene.button.onrelease(play)
screen.delay(20)
turtle.penup()
turtle.setposition(scene.button.xcor(), scene.button.ycor()-10)
turtle.pendown()
turtle.write("Move", align="center", font=("Arial",16,"bold"))
diameter = 1
dot_colour = "#ffff00"
x1 = 30 - scene.wnd_width/2; y1 = scene.wnd_height/3
x2 = scene.wnd_width/2 - 30; y2 = -scene.wnd_height/3
x_dot = x1; y_dot = y1
m = (y2 - y1) / (x2 - x1)
c = (x2*y1 - x1*y2) / (x2 - x1)
turtle.penup()
turtle.setposition(x_dot, y_dot)
turtle.setheading(0)
turtle.shape("classic")
turtle.shapesize(diameter, diameter)
turtle.color(dot_colour, dot_colour)
def play(x, y):
global x_dot, y_dot, m, c, x1, y1, restart
if restart:
turtle.clearstamps()
restart = False
if x_dot < scene.wnd_width/2 - 10*turtle.shapesize()[1]:
y_dot = m*x_dot + c
turtle.setposition(x_dot, y_dot)
turtle.stamp()
x_dot += 20
screen.ontimer(play(0,0), 500)
else:
x_dot = x1; y_dot = y1
restart = True
screen.mainloop()
scene = Template();
turtle = scene.controlButtons()
screen = scene.screen
prep()
Important: When trying to click on the button to get things
started, you might need to click away from the button text.