square roots with C++

Started by
5 comments, last by TheAdmiral 17 years, 4 months ago
how do i use them? i need them for a program i am making, but they aren't covered in the C++ book i have i tried making it by using X^.5 but it just generates an error
Advertisement
Try including math and using the function sqrt.
Note that although X ^ 2 will compile, it is not a power operation.

^ is a bitwise XOR operation.

To use powers of, you can use pow() from <cmath>, or for simple powers just write it out longhand ( eg: for X cubed use (X * X * X) )
#include <cmath>

And to do the actual calculation do sqrt(x) or sqrt(13) or whatever...
thanks, it works now
Just a note... the sqrt and pow functions are extremely slow (as they do huge number of multiplications and divisions), so if you have to use them a lot (such as in a loop), try to avoid them if possible.
I'll have to disagree, marshdabeachy.

On current hardware, the sqrt and pow functions aren't that slow, and they certainly don't perform many arithmetic operations.

While these particular floating-point operations are relatively slow compared to integer arithmetic, they are lightning-fast compared to any alternative implementation (especially on SSE hardware and the likes). If you need to calculate a square root or calculate a power, you won't do any better than these functions unless you sacrifice a great deal of accuracy. Considering that you can reel off billions of sqrt()s per second, I really wouldn't worry about micro-optimisations like this.

Regards
Admiral
Ring3 Circus - Diary of a programmer, journal of a hacker.

This topic is closed to new replies.

Advertisement