The Math Forum

Ask Dr. Math - Questions and Answers from our Archives
Associated Topics || Dr. Math Home || Search Dr. Math

Programming the Distance Formula

Date: 03/26/2001 at 22:26:50
From: Jean-Sebastien Payette
Subject: Program using one of your answers

I have a problem similar to one of your archived explanations. I would 
like to know how to use the concept you explained in "Using the 
Distance Formula" at:   

to be able to find the point on a line that's distance X from a given 
point, but in a computer-based programming language.

Date: 03/26/2001 at 23:22:39
From: Doctor Peterson
Subject: Re: Program using one of your answers

Hello, Jean-Sebastien.

There is a considerably simpler way to do this than what was shown in 
that answer. If you are at all familiar with vectors, you can follow 
my reasoning; otherwise just take the result.

Suppose we know two points A (x1,y1) and B (x2,y2) that determine a 
line, and want to find a point on that line that is d units from A, in 
the direction of B. Then the vector AB = (x2-x1,y2-y1) points in the 
right direction; its length is |AB| = sqrt((x2-x1)^2 + (y2-y1)^2). If 
we divide vector AB by its length, we get a unit vector AB/|AB| in the 
right direction; and if we then multiply this vector by length d, we 
get the vector AC that takes us to the desired point.

This means that point C is:

  C = A + AC = A + AB * d/|AB|

    = (x1,y1) + ---------------------------
                sqrt((x2-x1)^2 + (y2-y1)^2)

                    (x2-x1)d                        (y2-y1)d
    = (x1 + -------------------------, y1 + -------------------------)
            sqrt((x2-x1)^2+(y2-y1)^2)       sqrt((x2-x1)^2+(y2-y1)^2)

This should be easy to program.

- Doctor Peterson, The Math Forum   
Associated Topics:
High School Calculators, Computers
High School Coordinate Plane Geometry
High School Geometry

Search the Dr. Math Library:

Find items containing (put spaces between keywords):
Click only once for faster results:

[ Choose "whole words" when searching for a word like age.]

all keywords, in any order at least one, that exact phrase
parts of words whole words

Submit your own question to Dr. Math

[Privacy Policy] [Terms of Use]

Math Forum Home || Math Library || Quick Reference || Math Forum Search

Ask Dr. MathTM
© 1994- The Math Forum at NCTM. All rights reserved.