Home > other >  Haskell Area of general quadrilateral
Haskell Area of general quadrilateral

Time:11-20

I'm having trouble solving a problem in which I'm supposed to calculate the area of a general quadrilateral. I don't know exactly how to calculate the area and then implement it in the program. I looked it up and the area is probably calculated using the formula: A = ½·d1·d2·sin π where d1, d2 are the diagonals, which intersect at the angle π. But how do I implement this in the program?

My code looks like this:

data Point = MPoint Float Float
             deriving Show

class Polygon p where
  area_q :: p -> Float

data Quad = MQuad{
qP1 :: Point,
qP2 :: Point,
qP3 :: Point,
qP4 :: Point}
deriving Show
**Problem**
instance Polygon Quad where
   area_q (MQuad (MPoint x1 y1) (MPoint x2 y2) (MPoint x3 y3) (MPoint x4 y4)) = ((sqrt(x3-x1)^2*(y3-y1)^2)*(sqrt(x4-x2)^2*(y4-y2)^2)*sin(pi))/2

Well, that's how I implemented it, but when I use my examples, the result is 0, although the area is not equal to 0 (for my examples). Is the formula wrong or did I implement it wrong?

I appreciate the help and explanation, thank you in advance!

CodePudding user response:

You write

sin(pi)

which mimics your formula. But in your description of the formula, you say π is the intersection angle, whereas in the code, pi is 3.1415927 completely independently of the shape of the quadrilateral.

Additionally, you write

sqrt(x3-x1)^2*(y3-y1)^2

which corresponds to the math expression (√(x3 - x1))2(y3 - y1)2, but the correct formula for distance is √((x3 - x1)2 (y3 - y1)2).

  • Related