fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <math.h>
  5. #include <vector>
  6. using namespace std;
  7.  
  8. struct point
  9. {
  10. float x,y;
  11. };
  12.  
  13. float norm (point p) // get the norm of a vector
  14. {
  15. return pow(pow(p.x,2)+pow(p.y,2),.5);
  16. }
  17.  
  18. point trilateration(point point1, point point2, point point3, double r1, double r2, double r3) {
  19. point resultPose;
  20. //unit vector in a direction from point1 to point 2
  21. double p2p1Distance = pow(pow(point2.x-point1.x,2) + pow(point2.y- point1.y,2),0.5);
  22. cout<<"p2p1Distance ::: "<<p2p1Distance <<endl;
  23. point ex = {(point2.x-point1.x)/p2p1Distance, (point2.y-point1.y)/p2p1Distance};
  24. //cout<<"ex ::: "<<ex <<endl;
  25. point aux = {point3.x-point1.x,point3.y-point1.y};
  26. //cout<<"aux ::: "<<aux <<endl;
  27. //cout << "He has " << aux << " cats." << endl;
  28. //signed magnitude of the x component
  29. double i = ex.x * aux.x + ex.y * aux.y;
  30. //the unit vector in the y direction.
  31. point aux2 = { point3.x-point1.x-i*ex.x, point3.y-point1.y-i*ex.y};
  32. point ey = { aux2.x / norm (aux2), aux2.y / norm (aux2) };
  33. //the signed magnitude of the y component
  34. double j = ey.x * aux.x + ey.y * aux.y;
  35. //coordinates
  36. double x = (pow(r1,2) - pow(r2,2) + pow(p2p1Distance,2))/ (2 * p2p1Distance);
  37. double y = (pow(r1,2) - pow(r3,2) + pow(i,2) + pow(j,2))/(2*j) - i*x/j;
  38. //result coordinates
  39. double finalX = point1.x+ x*ex.x + y*ey.x;
  40. double finalY = point1.y+ x*ex.y + y*ey.y;
  41. resultPose.x = finalX;
  42. resultPose.y = finalY;
  43. return resultPose;
  44. }
  45.  
  46. int main(int argc, char* argv[]){
  47. point finalPose;
  48. point p1 = {4.0,4.0};
  49. point p2 = {9.0,7.0};
  50. point p3 = {9.0,1.0};
  51. double r1,r2,r3;
  52. r1 = 4;
  53. r2 = 3;
  54. r3 = 3.25;
  55. finalPose = trilateration(p1,p2,p3,r1,r2,r3);
  56. cout<<"X::: "<<finalPose.x<<endl;
  57. cout<<"Y::: "<<finalPose.y<<endl;
  58. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
p2p1Distance :::  5.83095
X:::  8.02188
Y:::  4.13021