Due: 8:00am, Thursday, February 18. Value: 30 pts. Submit to Sauron.
The centroid of a two-dimensional object is the point at which the object could be balanced on the tip of a finger. Write a program that reads a polygon from the user and displays its area and centroid. Below is a transcript illustrating how your program should work.
How many vertices? 4 Your interface should exactly match this. Coordinates for vertex 1? 0, 0 Coordinates for vertex 2? 10, 0 (In this example, we give the vertices Coordinates for vertex 3? 10, 10 of a 10×10 square.) Coordinates for vertex 4? 0, 10 The polygon's area is 100.0. The polygon's centroid is at (5.0, 5.0).
(The below section Computing a centroid provides formulas for computing these values. See also the Tips section for some tips on doing it in Python.)
Some other example test cases:
| Figure | Vertices | Area | Centroid |
|---|---|---|---|
Right triangle
| (0, 0)
(0, 10) (10, 0) | 50 | (3.33, 3.33) |
Parallelogram
| (0, 0)
(20, 0) (30, 20) (10, 20) | 400 | (15, 10) |
Hexagon
| (5, 0)
(15, 0) (20, 8.66) (15, 17.32) (5, 17.32) (0, 8.66) |
259.81 | (10, 8.66) |
We will let n represent the number of vertices in our polygon. Let x0 represent the first vertex's x-coordinate and y0 represent its y-coordinate. Similarly, let (x1, y1) be the location of the second vertex, and continue around the polygon over all its n vertices, so that (xn − 1, yn − 1) is the location for the final vertex. After that, we complete the polygon by letting (xn, yn) represent the first vertex's location again.
Knowing this, we compute A using the following formula; the area is the absolute value of A (i.e., |A|).
The centroid's x- and y-coordinates can be computed using the following formulas:
For example, for the right triangle with vertices at (0, 0), (0, 3), and (4, 0), we compute A as ½ ((0 ⋅ 3 − 0 ⋅ 0) + (0 ⋅ 0 − 4 ⋅ 3) + (4 ⋅ 0 − 0 ⋅ 0)) = ½ (0 + −12 + 0) = ½ (−12) = −6. Then we compute Cx as (1 / 6(−6)) ((0 + 0) (0 ⋅ 3 − 0 ⋅ 0) + (0 + 4) (0 ⋅ 0 − 4 ⋅ 3) + (4 + 0) (4 ⋅ 0 − 0 ⋅ 0)) = (−1 / 36) (0 ⋅ 0 + 4 ⋅ −12 + 4 ⋅ 0) = (−1 / 36) (−48) = 4 / 3. We can compute Cy similarly.
(The images given the formulas for A, Cx and Cy are taken from Wikipedia's centroid article.)
To read two numbers from the user on one line, you can place two variables on the left side of the assignment statement, separated by commas.
a, b = input('Give me two numbers: ')
If the computer executes this line and the user
enters 3, 4
, then the computer will
associate 3 with a
and 4 with b.
I recommend using two lists to store the coordinates, one for the x-coordinates and the other for the y-coordinates. If there are n vertices, then I would have each list with n + 1 entries, where the last entry is copied to match the first entry. This will allow a more straightforward translation of the formulas as given above.