Sign in to follow this  
alway616

square roots with C++

Recommended Posts

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

Share this post


Link to post
Share on other sites
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) )

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this