Click to See Complete Forum and Search --> : Really cheesy sqrt function
sail3005
Oct 23rd, 2001, 06:56 PM
int sqrt(int root){
int i = 0;
bool done = false;
while(!done){
i++;
if ((i*i) == root){done = true;}
else if (i == root){cout<<"No whole root";done = true;}
}
return i;
}
ok, this works with whole numbers, but i need something that will work with everything. Any ideas?
sail3005
Oct 24th, 2001, 05:42 AM
Anyone? Please?
kedaman
Oct 24th, 2001, 06:58 AM
I think Guv posted a way to approximate the squareroot of real numbers in math's forum
jim mcnamara
Oct 24th, 2001, 08:53 AM
Do you want the real way? - include math.h -- use sqrt(x)
Another calculated way? exp(log(x)/2)
There are loads of math functions. Edit math.h to see them.
c99 defines a lot fo new ones, MSVC++ aslo has a lot of non-standard add-ons.
sail3005
Oct 24th, 2001, 05:40 PM
kedaman -- thanks, i'll look for that.
Jim -- also, thanks. but, i am trying to do it from scratch, with my own code, not using any librarys.
Wynd
Oct 24th, 2001, 06:09 PM
Jim: If I look in math.h, I don't see any functions, just prototypes.
jim mcnamara
Oct 24th, 2001, 08:50 PM
Yes - prototypes. Then you can go into help and figure out which function does what.
I didn't realize that what was wanted was an iterative solution like by approximation, for sqaure root.
I posted some of these alogrithms and other similar ones in maths forum - none cheesy, but iterative.
Paul Hseih is a VERY good programmer:
http://www.azillionmonkeys.com/qed/sqroot.html
sail3005
Oct 25th, 2001, 04:46 PM
thanks jim, thats just what i was looking for.
BTW i have another question. Say i looked at it from a different angle. x^(1/2) is equal to the square root of x. so, i would think that you could make a more versitale function, covering cubed roots, etc. if you could somehow implement this method.
Now, i obviously know that to square a number, you multiply it by itself, but how do you mathematically raise a number to the (1/2) or (1/3) etc power?
thanks.
jim mcnamara
Oct 25th, 2001, 05:00 PM
Divide a number's logarithm by by n, then take exp
double root(double mantissa, double exponent){
if (exponent ==0) return 1;
if (exponent> 0)
return exp(log(mantissa) * exponent);
else
return exp( log(mantissa) / exponent );
}
usage:
v = root(2,-2) gives the sqrt of 2.
There is already a C, C++ function pow() that does this.
sail3005
Oct 25th, 2001, 05:03 PM
thanks again jim, and also for the prompt reply. But, i am trying to do it without dependency on math.h or other librarys. I am basically trying to learn to do this stuff myself.
Sorry to be a pain, but, do you have any other tips?
jim mcnamara
Oct 25th, 2001, 05:11 PM
Use Portal, the search engine for ACM. You have to register (free).
There are hundreds of articles on algorithms. ALot of them are in funky languages like Algol, but you can easily read it.
www.acm.org
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.