How to Calculate the Area of a Trapezoid in Python?
by María JoséC3 in Circuits > Software
1992 Views, 0 Favorites, 0 Comments
How to Calculate the Area of a Trapezoid in Python?
With this instructuable you will be able to know the area of any given trapezoid with the help of a program in python.
Download Python 2.7.10 and Necessary Libraries
Download python here:
https://www.python.org/downloads/
Download the libraries here:
Numpy and Matplotlib
The Are of a Trapezoid
The area of a trapezoid has the following equation:
A=(b+B)/2 + H
Where:
A is the area
B is the length of the longer base
b is the length of the smaller base
H is the height of the trapezoid
Building the Code
In order to build the code, you must have in mind that you must include:
- Libraries: Numpy and matplotlib.pyplot
- Allow the user to register the coordinates for the first two points.* (explanation in the picture)
- Convert the users information into the variables needed to calculate the area.
- Give the user the area of the trapezoid.
- Graph the trapezoid.
Final Code
import numpy as np
import matplotlib.pyplot as plt
x=[] y=[]
x1=float(input("Ingrese la coordenada en X del primer punto ")) y1=float(input("Ingrese la coordenada en Y del primer punto "))
x2=float(input("Ingrese la coordenada en X del segundo punto ")) y2=float(input("Ingrese la coordenada en Y del segundo punto "))
P1=(x1,y1) P2=(x2,y2) P3=(x1,0) P4=(x2,0)
B=np.sqrt(((x2-x1)**2)+((y2-y1)**2)) ##B es la longitud de la base mayor b=(x2-x1) ##b es la longitud de la base menor h=y2 ##h es la altura del trapecio.
area=((B+b)/2)*h
print("El area del trapecio es",area) plt.plot([x1,x2,x2,x1,x1],[0,0,y2,y1,0]) #grafica los puntos del trapecio plt.axis([-1,20,-1,20]) #Limita la longitud de los ejes plt.fill_between([x1,x2,x2,x1,x1],[0,0,y2,y1,0]) #llena el espacio entre puntos plt.show()