Advertisement

Square Root

Started by January 03, 2003 05:17 PM
13 comments, last by Tech19 21 years, 10 months ago
Could anyone explain how i can find the square root of a number in c++? Is there allready a function for it? even if so i am quite interested in how the answer is found. the only way i thought of is x/n = n in a loop increasing the value of n until the expression is true but that would take ages and ages especially if the roots a decimal value. thanks.
#include <cmath.h>

functions:
float sqrt(float num);
double sqrt(double num);
long double sqrt(long double num);

this will return the square root of num, hope this helps!
Advertisement

  #include <math.h>double Number = 9;double Answer = sqrt(Number);  


Alan
"There will come a time when you believe everything is finished. That will be the beginning." -Louis L'Amour
it uses the fsqrt instruction

My Site
"even if so i am quite interested in how the answer is found."
There is an ASM instruction, SQRT(?) which gives you the answer. The compiler just uses that instruction.

Height Map Editor | Eternal lands
Be aware that sqrt can be slow, relatively speaking. I wouldn''t use it in a tight loop.

Instead of :
if (x < sqrt (y))
...

use

if (x * x < y)
...
Advertisement
can anyone please explain why you do the things your suggesting? Just giving someone the code does them little good. Then they are using the code and not knowing why.

-----------------------------
Programming is confussing!
AIM: Trebor DoD
-----------------------------AIM: Trebor DoDHompage: Thinking Digitally: My Web Blog
A few methods for finding square roots may be found here. I honestly don't see, however, why the average programmer should be particularly concerned with the inner workings of whatever algorithm the processor uses for this ...


The Corner of Misery
Artwork and writing

[edited by - Miserable on January 3, 2003 8:38:21 PM]
I would have thought that the code was pretty simple to understand - call the sqrt() passing an integer/float as a parameter, the function then returns the square root of the passed int/float.
quote: Original post by Digigamer15
can anyone please explain why you do the things your suggesting? Just giving someone the code does them little good. Then they are using the code and not knowing why.\


The sqrt function is very simple and straightforward, nothing really to explain. Or are you referring to Anonomous poster''s reply about which way you should do certain operations. If so, then the reason would be because sqrt takes longer to process. Internally, it probably does alot of checks to see which two same numbers when multiplied together result in that value, which does take time. I do know that there are other mathematical ways of finding square roots without trial and error or narrowing down, but I''m unsure if C++ uses them.

This topic is closed to new replies.

Advertisement