Square root slightly off
Nov 19, 2016 at 3:55am UTC
Hi, I was supposed to write a basic recursive square root function but the values it returns are slightly off. Im not sure whats wrong, and help would be appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include<iostream>
#include<cmath>
#include<cfloat>
#include<string>
#include <cstdlib>
using namespace std;
//declare sqroot function calls recursive function newton
double sqroot1(double num );
double newton(double num, double guess);
int main(int argc, char **argv)
{
if ( argc < 2 )
{
return -1;
}
for ( int i = 0 ; i < argc ; i ++)
{
cout<<"sqroot(" <<argv[i+1]<<") is " << sqroot1(atoi(argv[i+1])) <<endl;
}
}
double newton(double num, double a)
{
if ((abs(a*a - num) <= FLT_EPSILON))
{
return a;
}
else
{
newton(num, (a+num/a)/2 );
}
}
double sqroot1(double num)
{
double sqrt = newton(num,num/2);
return sqrt;
}
Nov 19, 2016 at 4:21am UTC
That is to be expected due to
if ((abs(a*a - num) <= FLT_EPSILON))
.
You will only get the precision of a float (typically 7 digits). Use numeric_limits<float >::digits10
to find out how much precision you can get.
http://www.cplusplus.com/reference/limits/numeric_limits/
I think I'm wrong on this.
Last edited on Nov 19, 2016 at 4:30am UTC
Nov 19, 2016 at 5:35am UTC
You're missing a return statement on line 34; in the recursive case, control will reach the end of the function without returning a value.
Nov 19, 2016 at 8:47am UTC
You need to:
- return a value on line 34 (as mbozzi says above)
- use atof(), not atoi(), for doubles in line 20
- if you use i+1 in line 20, then it needs to be argc-1, not argc in line 18
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include<iostream>
#include<cmath>
#include<cfloat>
#include<string>
#include <cstdlib>
using namespace std;
//declare sqroot function calls recursive function newton
double sqroot1(double num );
double newton(double num, double guess);
int main(int argc, char **argv)
{
if ( argc < 2 )
{
return -1;
}
for ( int i = 0 ; i < argc - 1; i ++) // <=== argc - 1, not argc
{
cout<<"sqroot(" <<argv[i+1]<<") is " << sqroot1(atof(argv[i+1])) <<endl; // <=== atof, not atoi
}
}
double newton(double num, double a)
{
if ((abs(a*a - num) <= FLT_EPSILON))
{
return a;
}
else
{
return newton(num, (a+num/a)/2 ); // <=== return a value (as per mbozzi suggestion)
}
}
double sqroot1(double num)
{
double sqrt = newton(num,num/2);
return sqrt;
}
Running
newton.exe 4 6.25 0.25 25
gives as output
sqroot(4) is 2
sqroot(6.25) is 2.5
sqroot(0.25) is 0.5
sqroot(25) is 5
Topic archived. No new replies allowed.