Search code examples
pythonmathshapesarea

Calculate the area of a quadrilateral


I'm trying to create a calculator which calculates the area of a simple quadrilateral. I know that every quadrilateral can be split into two triangles, and I should be able to calculate the area in two parts no matter what. I am able to do this in math, but I don't know how to implement it to Python.

Here's my quadrilateral class:

class Quadrilateral(Shape):
   def __init__(self, name):
       # in clockwise order: angles[0], sides[0], angles[1], sides[1], ...
       self.sides = [5] * 4
       self.angles = [90] * 4
       super().__init__(self, name)

Now what I need is to implement a method get_area() which calculates the area of my quadrilateral, but I have no idea how.

Here's how I would do it with a paper and a pen:

Area of a quadrilateral

Basically I would only need to know two angles and three sides to be able to use this technique to calculate the area, but let's not worry about that. For now, I know all the angles and all the sides, how do I calculate the area?


Solution

  • Just access the sides and angles directly in the two lists you have:

    import math
    
    area1 = 0.5 * self.sides[0] * self.sides[1] * math.sin(math.radians(self.angles[1]))
    area2 = 0.5 * self.sides[2] * self.sides[3] * math.sin(math.radians(self.angles[3]))
    area = area1 + area2
    

    Given your example as sides = [3, 5, 5, 4] and angles = [90, 95, 75, 100], the area then is:

    >>> import math
    >>> sides = [3, 5, 5, 4]
    >>> angles = [90, 95, 75, 100]
    >>> area1 = 0.5 * sides[0] * sides[1] * math.sin(math.radians(angles[1]))
    >>> area2 = 0.5 * sides[2] * sides[3] * math.sin(math.radians(angles[3]))
    >>> area1 + area2
    17.31953776581017