DEV Community

Slope Calculator
Slope Calculator

Posted on

Slope Calculator Guide: Formula, Examples and Python Code

`Slope tells you how steep a line is and which direction it leans. It appears in algebra, road design, roofing, ramps and data analysis.

The slope formula

Slope (m) is the vertical change (rise) divided by the horizontal change (run):

m = (y2 - y1) / (x2 - x1)
Enter fullscreen mode Exit fullscreen mode




Worked example

Take the points (2, 3) and (6, 11).

  1. Rise: 11 - 3 = 8
  2. Run: 6 - 2 = 4
  3. Slope: 8 / 4 = 2
  4. y-intercept: 3 - (2 × 2) = -1
  5. Equation: y = 2x - 1

Four types of slope

Type Meaning
Positive Line rises from left to right
Negative Line falls from left to right
Zero Horizontal line
Undefined Vertical line (run is 0)

Slope, angle and percent grade

  • Angle = arctan(m)
  • Percent grade = m × 100

A road rising 3 m over a horizontal 60 m has a slope of 0.05, a 5% grade and an angle of about 2.86°.

Where slope is used

  • Ramps: US ADA standards set a maximum running slope of 1:12 for ramps.
  • Roofs: A 6:12 pitch is a slope of 0.5, about 26.57°.
  • Data: The slope of a trend line shows how fast one value changes with another.

Calculate slope in Python

`python
import math

def slope(x1, y1, x2, y2):
if x1 == x2 and y1 == y2:
raise ValueError("The two points must be different")
if x1 == x2:
return None, 90.0 # vertical line
m = (y2 - y1) / (x2 - x1)
return m, math.degrees(math.atan(m))

print(slope(2, 3, 6, 11)) # (2.0, 63.43...)
`

Common mistakes

  • Subtracting the points in a different order on top and bottom
  • Dividing run by rise
  • Mixing units, such as metres and centimetres
  • Calling a vertical line's slope zero

Check your answer

I run a free slope calculator that shows step-by-step working and a graph, so you can compare it with your hand calculation.

This article was created with the help of AI.`

Top comments (0)