0

So, I am trying to return the square root of a number in two ways, which in my view are not so different. Which of these would have a higher accuracy and why? As far as I can tell the second would be the better one, as I believe the default "allowed error" (not sure how that is called) is much lower than my set variable 'eps': 0.00001. Is that correct? Does this have to do with Codeblocks or the compiler or the processor itself?

First method :

#include <iostream>
using namespace std;
int main()
{
    double a,b;
    double x;
    cin>>x;
    int nr=0;
    //double eps=0.00001;
    a=1;
    do
    {
        b=a;
        a=(b+x/b)/2;
        nr++; //used to keep track of number of steps made
    }while(a!=b);
    cout<<a;
return 0;
}

Second method would be the same, except for the do...while() condition:

#include <iostream>
using namespace std;
int main()
{
    double a,b;
    double x;
    cin>>x;
    int nr=0;
    double eps=0.00001;
    a=1;
    do
    {
        b=a;
        a=(b+x/b)/2;
        nr++;
    }while(a-b>=eps || b-a>=eps);
return 0;
}
M.Ionut
  • 187
  • 1
  • 3
  • 15
  • `while(a!=b)` is comparing two floating point numbers using equality, which is generally not the accepted way to do it. See https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison – Robert Harvey Jan 04 '19 at 16:31
  • 1
    There is no default allowed error so your first program has pretty high change not to finish at all. – Slava Jan 04 '19 at 16:32
  • It's not about prevision. The `a!=b` comparison might not work as you expect. Floating point math is [not perfectly precise](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) and may operations introduce rounding errors. – François Andrieux Jan 04 '19 at 16:32
  • 1
    You may be interested in [`std::numeric_limits::epsilon()`](https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon). – François Andrieux Jan 04 '19 at 16:34
  • 1
    See also https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ – Robert Harvey Jan 04 '19 at 16:37
  • Thank you all a lot! Sorry for the duplicate question! – M.Ionut Jan 04 '19 at 16:38

0 Answers0