Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Square root program doesn't produce the right value (http://www.velocityreviews.com/forums/t449691-square-root-program-doesnt-produce-the-right-value.html)

 Protoman 11-10-2005 04:14 AM

Square root program doesn't produce the right value

Can you help me? For 4, my square root funct gives 4 instead of 2;
here's the code:

#include <iostream>
#include <cstdlib>
using namespace std;

template<class T>
T Abs(T Nbr)
{
if( Nbr >= 0 )
return Nbr;
return -Nbr;
}

template<class T>
T Sqrt(T Nbr)
{
long double Number = Nbr / 2;
const long double Tolerance = 1.0e-7;
do Number = (Number + Nbr / Number) / 2;
while( Abs(Number * Number - Nbr) > Tolerance);
return Number;
}

int main()
{
cout << "Enter a number: " << endl;
long double num;
cin >> num;
cout << "Sqrt(" << num << ")= " << Sqrt(num) << endl;
system("PAUSE");
return 0;
}

Can you help me? Thanks.

 Kai-Uwe Bux 11-10-2005 04:21 AM

Re: Square root program doesn't produce the right value

Protoman wrote:

> Can you help me? For 4, my square root funct gives 4 instead of 2;
> here's the code:
>
> #include <iostream>
> #include <cstdlib>
> using namespace std;
>
> template<class T>
> T Abs(T Nbr)
> {
> if( Nbr >= 0 )
> return Nbr;
> return -Nbr;
> }
>
> template<class T>
> T Sqrt(T Nbr)
> {
> long double Number = Nbr / 2;
> const long double Tolerance = 1.0e-7;
> do Number = (Number + Nbr / Number) / 2;
> while( Abs(Number * Number - Nbr) > Tolerance);
> return Number;
> }
>
> int main()
> {
> cout << "Enter a number: " << endl;
> long double num;
> cin >> num;
> cout << "Sqrt(" << num << ")= " << Sqrt(num) << endl;
> system("PAUSE");
> return 0;
> }
>
> Can you help me? Thanks.

Hm, on my machine, the program computes "Sqrt(4)= 2" just fine. The real
problem is "Sqrt(0)= nan".

Here is a fix for that:

template<class T>
T Sqrt(T Nbr)
{
long double Number = Nbr / 2;
const long double Tolerance = 1.0e-7;
while( Abs(Number * Number - Nbr) > Tolerance) {
Number = (Number + Nbr / Number) / 2;
}
return Number;
}

Best

Kai-Uwe Bux

 Karl Heinz Buchegger 11-10-2005 09:51 AM

Re: Square root program doesn't produce the right value

Protoman wrote:
>
> Can you help me? For 4, my square root funct gives 4 instead of 2;
> here's the code:
>

What's wrong with fireing up your debugger and stepping through the code
to see why it does that?

Figuring out problems in code and why it doesn't do what it should do
is *vital* in becomming a programmer. So start early, develop your
skills and learn how to use your tools.

--
Karl Heinz Buchegger