I am trying to calculate the area of a triangle positioned on cartesian coordinates.
The triangle is formed from three points:
- a
- b
- c
Each point has two coordinates:
- x
- Y
My logic is the following:
- calculate the distance between point a and point b call it base
- calculate a point exactly in the middle of a and b (bisector I think it is called)
- get the distance between midpoint of a and b and point c and call it height
- Calculate the area with the formula base times height over two
The logic seems appropriate to me, but I'm not passing the unit tests in the exercise.
This is my code:
function distance(x1,x2,y1,y2){
return Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2));
}
function area(b,h){
return (b*h)/2;
}
function midlePoint(x1,x2,y1,y2){
return new Point((x1+x2)/2,(y1+y2)/2);
}
function triangleArea(triangle){
var {a,b,c} = triangle;
var {x:x1,y:y1} = a;
var {x:x2,y:y2} = b;
var base = distance(x1,x2,y1,y2);
console.log(base);
var {x:midlex,y:midley} = midlePoint(x1,x2,y1,y2);
var {x:x3,y:y3} = c;
var height = distance( midlex,x3,midley,y3);
console.log(height);
return area(base,height);
}
These are the unit tests:
Test.assertEquals(+triangleArea(new Triangle(new Point(10, 10), new Point(40, 10), new Point(10, 50))).toFixed(6), 600)
Test.assertEquals(+triangleArea(new Triangle(new Point(15, -10), new Point(40, 20), new Point(20, 50))).toFixed(6), 675)
What will be the problem?
ISSUE
Your problem is that you mistakenly assume that the height of your triangle passes through the midpoint of what you set as the base. Your logic holds only for isosceles triangles and when you choose the base properly.
SOLUTION
To calculate the area of any triangle, given its vertices, you must use a different algorithm than the one you are trying to implement.
The formula is given by:
Where
|nAB·AC|
is the absolute value of the dot product or scalar product of the vectorsnAB
andAC
. BeingnAB
the normal vector (perpendicular) toAB
Step 1. Calculate the vector
AB: (Xb - Xa, Yb - Ya) = (Xab,Yab)
Step 2. You calculate the normal vector to AB (it is the direction of the vector perpendicular to AB)
nAB: (Xn, Yn) = (Yab, -Xab)
Step 3. Calculate the vector
AC: (Xc - Xa, Yc - Ya) = (Xac,Yac)
Step 4. Calculate the dot product (scalar product) of the vectors nAB and AC: (Xn * Xac) + (Yn * Yac)
Step 5. You calculate the Area of the triangle applying the formula: A = (1/2)(|scalarproduct|)
RESULT
How can your role be? Well, that's up to you, I'll just give you an example:
I hope this clears your doubt.
Cheers
References:
Isosceles triangle - Wikipedia
Scalar Product - Wikipedia