# Developers Planet

carol February 2016

### I use x=a+x-x^2 and set g(x)=a+x-x^2 to find the positive square root of the positive parameter a

``````// Convergence to a root of an equation

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

/* compute g(x) with parameter a */
double g(double a, double x) {
double y=0.0;
y=a+x-x*x;
return y;
}

/* compute the term x_n in the sequence given x0 and the parameter a */
double nthterm(double a, double x0, int n) {
for(int i=0;i<=n-1;i++) x0=g(a,x0);
return x0;
}

int main () {
double a; // parameter
int n; // number of steps to do
double x0; // initial guess
cout << "input a,x0,n: " << endl;
cin >> a >> x0 >> n;
cout << "param a=" << a << " guess=" << x0 << " number of terms=" << n << endl;
cout << nthterm(a,x0,n) << endl;
return 0;
}
``````

I use x=a+x-x^2 and set g(x)=a+x-x^2 to find the positive square root of the positive parameter a. It compile well, but I can't get the right answer from my code.

Xaver February 2016

The problem is that the series you create with nthterm does not converge. Try to change the line

``````y=a+x-x*x;
``````

to

``````y=(x+a/x)/2;
``````

EDIT: The code works if and only if the start value is not zero. For positive start values you get the positive square root; for negative start values you get the negative square root.