Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a special function for Absolute Value of a Vector

Status
Not open for further replies.

Sunny2

Programmer
Sep 11, 2003
15
CA
Hi guys,

I am just wondering if there is any special function to find the absolute value of a vector. I have the x coordinate and the y coordinate. I dont' want to be finding the sqrt of the x and y terms allt he time, I am sure there is a function, but if you guys know, that would be a great help. Thank you.

Sunny
 
use function pow declared in math.h

Ion Filipski
1c.bmp
 
Math vector notion != STL vector type.
There are no math vectors in C/C++ RTL (2D? 3D?;) => no any math vector length functions...
 
as I can see user does not mean STL vector. He wants a
sqrt (x^2 + y^2) where x and y are coordinates of a R2 (ie 2D) vector. So in C++ it is pow(x*x + y*y, 0.5). To make an RXXX vector in STL is enouch to create a vector<double> with XXX elements and sum the squares of each element. After that use pow(result, 1 / 2) to get length.

Ion Filipski
1c.bmp
 
Do what Ion said, but use sqrt() instead. On my computer, using sqrt takes less than a sixth of the time that pow(..., .5) takes. Many times you don't need to take the sqrt and can simply use the square of the distance instead, which is much faster to compute, so be on the lookout for those situations. An example of one would be where you need to check if something is within, say, 15 units. Instead of saying something like if(sqrt(x*x + y*y) < 15), square both sides and say if(x*x + y*y < 225). Another example would be projection, where you must divide by the square of the norm, so the square root goes away.

Just a note, it's now standard to #include <cmath> instead of the old C header file math.h. There's really no difference and all cmath does is #Include <math.h>, but cmath is prefered over math.h for the same reason that iostream is over iostream.h. I don't understand it, but it's the convention.
 
Hello guys,

Thanks for your reply, but I just founda special function to do that.

you could simply use the hypot function.
for example: hypot(x,y);

will give you the hypotenuse of that vector.

well, anyways, Thanks again.

Sunny
 
yes, it is good for 2D vectors, but for 3D or XXXD it is not good.

Ion Filipski
1c.bmp
 
yes, you are rite Ion. Thanks again.

Sunny
 
Warning: hypot() is not ANSI/ISO C/C++ Standards library function...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top