p1 = (-3, 1) p2 = (5, 7)
Notes and Code | Outcome |
---|---|
Plotting pointsFirst, let's plot the points. We'll do it a little differently from some of the other lessons because we want to make all these calculations about the points.
Lines 6&7: The two points are created as vectors and named
Lines 10: Since the points are vectors, when we create sphere for the first point, we can set the position by using p1:
Line 14: We can also use
Line 17: One of the reasons we're making the points vectors is that vectors have a few useful properties. One of these is the fact that you can refer to the x-coordinate of the vector using the dot notation. So, p1's x-coordinate is
|
Full program for plotting two points
|
Slope EquationThe slope between two points is given by: $$ m = \dfrac{y_2 - y_1}{x_2 - x_1} \tag{1}$$
|
⇨
|
Slope FunctionNow we'll write a function to get the slope. $$ m = \dfrac{y_2 - y_1}{x_2 - x_1} \tag{1}$$Inputs: As you can see from the equation, you need four values (x1, y1, x2, and y2) to calculate the slope. Output/s: The equation calculates one value, the slope, so there will be only one output from our function. Writing and Calling the FunctionThe slope Function
The function is defined on Lines 1-3
Line 2:
Line 3: Here we calculate the slope.
Line 4: Here we return the value of the slope ( Calling the slope functionFunctions stand alone. When you run the program, the function definition is stored in memory and saved until the function is called.
Line 19: The function is called by using its name, and passing the input values. The function returns the result to the place in the code where the function is called. WE could have also called the function and passed the x and y values directly like:
This function call is a little clunky with the four inputs, so next we'll create another function that takes two vectors as inputs. |
Code with slope function:
|
Function using vectors as inputs.Line 26: The call to the new function is much simpler and, hopefully, more intuitive, now you sent only two values, the vectors for the two points.
Line 7-9: The new function, called
Local Variables: Notice that both functions ( |
Show Notes ▼
|
Distance FunctionWrite a function that calculates the distance between the two points. The equation is: $$ d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$ |
Show Notes ▼
|
Intercept FunctionWrite a function that calculates the intercept of the line that passes through the points: |
Show Notes ▼
|
Distance along a curveGenerate a number of points, and use your distance function to calculate the total distance along the curve. |
Number of points:
Check your answer (total distance):
Show Notes ▼
|