# Gradient of a line segment

### From Devipedia

In our first example, we calculated the length of a line segment using the Pythagorean theorem and two points. To check our answer we drew an extra horizontal line with our answer as the length and did a visual comparison. But it's difficult to visually compare the length of two lines when one is drawn at an angle and another drawn flat horizontally.

Our test would be a bit better if we could draw the comparison line at the same angle, or gradient, as the first line. Then our eyes would be able to better judge if the lines are the same length.

So what is the gradient of our first line? It turns out we can find using only our two original points as inputs.

**gradient = (y1-y2)/(x1-x2)**

In our example gradient turns out to be .5. To draw a line the length of our original line segment and at the same gradient (also known as slope), we will need to convert our gradient value to degrees. We'll use turtle.left() to "point" in the direction we want to move, and then turtle.forward() to draw the new line segment.

The larger the absolute value of a gradient, the steeper the line. A horizontal line has slope 0, a 45° rising line has a slope of +1, and a 45° falling line has a slope of -1. A vertical line's slope is undefined meaning it has "no slope."

We need a function that will convert our gradient value to a degree. This formula should fit the bill.

http://upload.wikimedia.org/math/9/8/6/98653a4ca9ed801e97dcbcd08ad1e81e.png

We'll use math.atan(), which returns the arc tangent of "gradient", in radians. And since turtle.left() requires degrees as input, we'll convert the radians returned by atan() to degrees like so:

>>> degrees(atan(.5)) 26.56505117707799

Since we know that line with slope 1 is 45°, let's also quickly test this value to make sure our function works as expected.

>>> degrees(atan(1)) 45.0

Very good. We get the expected answer.

Let's modify our original example to use this function and then check out the results.

from turtle import * from math import * setworldcoordinates(-15,-15,15,15) # define our points x1 = 12.0 x2 = 2.0 y1 = 8.0 y2 = 3.0 penup() goto(x1,y1) pendown() dot(10, 'red') # the first point goto(x2,y2) # draws a thin line to the second point dot(10, 'red') # the second point gradient = (y1-y2)/(x1-x2) penup() # pick up our pen goto(x2+1, y2) # move to the right a bit to get ready to draw our comparison line pendown() # calculate the length of the hypotenuse c = sqrt( pow((x1-x2),2) + pow((y1-y2),2)) # Draw a line the length of c and visually check # our result by comparing the length to our original line. d = degrees(atan(gradient)) left(d) # turn the pointer to the left d degrees forward(c) # Draw a line segment the length of our original line segment """ Visually compare. Do the lines appear to be the same length, angle, and are they parallel? """

Next: Equation of a line