c++ - 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 root of equation #include <iostream> #include <cstdlib> #include <cmath> using namespace std; /* compute g(x) parameter */ double g(double a, double x) { double y=0.0; y=a+x-x*x; return y; } /* compute term x_n in sequence given x0 , parameter */ 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 double x0; // initial guess cout << "input a,x0,n: " << endl; cin >> >> x0 >> n; cout << "param a=" << << " guess=" << x0 << " number of terms=" << n << endl; cout << nthterm(a,x0,n) << endl; return 0; } i use x=a+x-x^2 , set g(x)=a+x-x^2 find positive square root of positive parameter a. compile well, can't right answer code.
the problem series create nthterm not converge. try change line
y=a+x-x*x; to
y=(x+a/x)/2; edit: code works if , if start value not zero. positive start values positive square root; negative start values negative square root.
Comments
Post a Comment