I want to calculate the area of any polygon by entering its coordinates, I made the function to calculate the area according to the formula that is in the image and when I run the program the value of the area is wrong.
Point 1:
n=int(input("Ingrese el número de lados del polígono:"))
x=[]
y=[]
vértices=[]
for i in range(n):
coordenada_x=int(input("Ingrese el valor de la coordenada x"+str(i)+":"))
coordenada_y=int(input("Ingrese el valor de la coordenada y"+str(i)+":"))
x.append(coordenada_x)
y.append(coordenada_y)
vértices.append(coordenada_x,coordenada_y)
x.append(x[0])
y.append(y[0])
Point 2:
from entrada import n
from entrada import x,y
for i in range(n):
Suma=(x[i]*(y[i+1]-y[i-1]))
Área_Polígono=(1/2)*abs(Suma)
print("Área del polígono=:",Área_Polígono,"U^2")
When running the program:
Ingrese el número de lados del polígono:3
Ingrese el valor de la coordenada x0:0
Ingrese el valor de la coordenada y0:0
Ingrese el valor de la coordenada x1:1
Ingrese el valor de la coordenada y1:0
Ingrese el valor de la coordenada x2:1
Ingrese el valor de la coordenada y2:1
Coordenadas_x=[0,1,1,0]
Coordenadas_y=[0,0,1,0]
Vértices=[(0,0),(1,0),(1,1)]
The error occurs with the area, since the following appears:
Área del polígono=0.0 U^2
When the area in this case should be 0.5 U^2
You have the problem in:
What this does is create a new list using a literal:
that contains as first element the last coordinate added in the
for
:and as second the first coordinate (index 0 of the list):
and that new list adds it to the end of the list you already had as a new item, in your case:
Actually you have complicated yourself a lot without need, you just need to do:
The list is assumed to have at least one element, it actually must have at least 3 by the polygon definition itself, which you can consider validating in case the user enters
n < 3
.To iterate by grouping the pairs x, yof each coordinate you can:
It is best to use the builtin
zip
:for in
+enumerate
+ indexed:Indexing with
for
yrange
(the least efficient and pythonic):Or if you want a new list with the pairs of coordinates per vertex:
or generate the list directly in the
for
:In both cases it would iterate the same: