Jump to content

Need help with Square Root function

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
Gz1987

Gz1987

    Newbie

  • Members
  • Pip
  • 9 posts
I am a little lost on the squareRoot function i got from class.

ok the purpose of the program is return the square root value.

heres what i got so far.

Quote

#include <iostream.h>
#include <fstream.h>

double absValue(double x)
{
if (x<0)
return -x;
else
return x;
}

double squareRoot(double x)
{
double y;
y=x;
while (absValue(y*y)>.0001){ // why y*y, i don't understand this part
//seems like it will make it into an infinite
//loop
y = (y+x/y);
}
return y;
}

int main()
{
double x;
cin>>x;
cout<< squareRoot(x);

cin>>x; // to pause window from closing
}



The absolute value function work without any problem, but i don't understand the squareRoot function. it looks like the Babylonian method for square root, but then again i am not sure. any help will be appreciated.

#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
That function is indeed confusing how it's written... unless I missed something y has to be less than .01 and greater than -.01 to escape the loop, so it shouldn't ever return results other than that. Are you intended to fix this program or is it only an example?

Also, absValue is completely worthless where it is. No matter the value for y, negative or positive, when you multiply it by itself it's going to be a positive value.

Yeah, unless I very much missed something, this doesn't make any sense at all.
Wow I changed my sig!

#3
Gz1987

Gz1987

    Newbie

  • Members
  • Pip
  • 9 posts
Thx for the quick reply.

Haha, i guess the instructor just want us to know how to write an Absolute value function.

i agree it's very confusing. but i did make 2 changes to the original code i got from the instructor. i skipped a day of class, so i am not sure if the code i got is complete or i have to add few more lines to it.

double squareRoot(double x){
double y;
y=x;
while(absValue(y*y>.0001){       //first change here(Missing " ) "? 
       y=(y+x/y)                        //second change here(Missing ";")
        }
       return(y);
}


#4
wiwbiz

wiwbiz

    Learning Programmer

  • Members
  • PipPipPip
  • 67 posts
I don't see how the square root is ever less than the number itself here. Basically I didn't see this method for finding square roots anywhere.

#5
theonejb

theonejb

    Learning Programmer

  • Members
  • PipPipPip
  • 52 posts
The while loop condition makes more sense like this:

double y;
y=x;
while(absValue(y*y - x)>.0001){       
   // do the calculation here
}
return(y);
}