Reputation: 79
I am trying to find whether the given triangle has its origin inside or outside.
The code below always gives Origin is not inside given triangle. I have no idea why is it so and how to fix it.
float distance(int x1, int y1,int x2,int y2)
{
int dis = (((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)));
float dis1 = sqrt(dis);
return dis1;
}
float AreaOfTriangle(float a, float b, float c)
{
float s = (a+b+c)/2;
float Area = sqrt(s*(s-a)*(s-b)*(s-c));
cout << Area << endl;
return Area;
}
int main()
{
float dis1 = distance(-1,-1,0,1);
float dis2 = distance(1,-1,-1,-1);
float dis3 = distance(0,1,1,-1);
float area = AreaOfTriangle(dis1,dis2,dis3);
float dis4 = distance(0,0,-1,-1);
float dis5 = distance(0,0,1,-1);
float area1 = AreaOfTriangle(dis2,dis4,dis5);
float dis6 = distance(0,1,0,0);
float area2 = AreaOfTriangle(dis1,dis4,dis6);
float area3 = AreaOfTriangle(dis3,dis5,dis6);
float a = area1 + area2 + area3;
cout << endl << a;
if(area == a)
{
cout << "Origin is Inside Given Triangle";
}
else
{
cout << "Origin is not Inside Given Triangle";
}
return 0;
}
Upvotes: 2
Views: 756
Reputation: 6171
I think you can do this
Consider points a,b and c (ax,ay),(bx,by) and (cx,cy)
define A = ax + ay, B = bx + by and C = cx + cy
Define z = y (B/A) + (1 -y) (C/A)
Calculate z for y=0 and y = 1. If either or both values are between 0 and 1 then the triangle contains the origin
Upvotes: 1
Reputation: 811
Given points a,b,c.
Of course, this is very general and can also be extrapolated to any point, and the first 3 steps are optimizations. There are also little kinks that'll need to be worked out in the implementation, but should hold true.
You'll need to figure out how to properly do floating point math though.
Upvotes: 0