-1
#include<iostream>
#include<cmath>
using namespace std;
int e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    if(fabs(yk(k,x)*yk(k,x) - x)<e) return yk;
    return square(x,k+1);    
}
int main()
{    
    cout<<yk(5,2);
    return 0;
}

I need to calculate the square root of a number with Newton's formula which calculates y[k] till fabs(y[k] * y[k] -x)>e (a small number like 0.0001);

So if sqrt (2)= 1.41421356237 and e=0.0001 my function must back 1.4142 .

..This is the program I wrote.. I know that it is buggy, so i will be very thankful if sb help me :)))

Paul Floyd
  • 3,765
  • 5
  • 25
  • 37

1 Answers1

1

The variable e should be float or double.
The error you get is not because of the fabs function, it is because you are trying to return a pointer to the yk function, but square returns a double

#include <iostream>
#include <cmath>

using namespace std;
double e=0.001;
double yk(int k,double x){
    if(k==0) return 1;
    return 0.5*(yk(k-1,x) + x/yk(k-1,x));
}

double square(double x,int k)
{
    double res = yk(k, x);
    if (fabs(res*res - x) < e) return res;
    return square(x,k+1);
}

int main()
{
    cout << yk(5,2); // Actually you don't call square....
    // it works even if you do square(2, 5), this way you get the root of two
    // doing at least 5 iterations, and if it is not enough (error > e) the
    // computer goes on until it gets an error < e
    return 0;
}
Alex
  • 821
  • 10
  • 12
  • 2
    You've correctly added `double res = yk(k,x)` to function `square` but the same optimization must also be applied to function `yk` itself for the `yk(k-1,x)` expression. – MSalters Jan 25 '15 at 14:20