C++ 我使用x=a+;x-x^2和集g(x)=a+;x-x^2查找正参数a的正平方根 //收敛到方程的根 #包括 #包括 #包括 使用名称空间std; /*用参数a计算g(x)*/ 双g(双a,双x){ 双y=0.0; y=a+x-x*x; 返回y; } /*计算给定x0和参数a的序列中的项x_n*/ 双n项(双a,双x0,整数n){ 对于(inti=0;i>x0>>n; cout

C++ 我使用x=a+;x-x^2和集g(x)=a+;x-x^2查找正参数a的正平方根 //收敛到方程的根 #包括 #包括 #包括 使用名称空间std; /*用参数a计算g(x)*/ 双g(双a,双x){ 双y=0.0; y=a+x-x*x; 返回y; } /*计算给定x0和参数a的序列中的项x_n*/ 双n项(双a,双x0,整数n){ 对于(inti=0;i>x0>>n; cout,c++,C++,问题是您用n项创建的序列不收敛。请尝试更改行 // 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*

问题是您用n项创建的序列不收敛。请尝试更改行

// 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;
}


编辑:当且仅当起始值不为零时,代码才起作用。对于正起始值,你得到正平方根;对于负起始值,你得到负平方根。

你确定你的级数收敛吗?是的,但对于大n,我确实无法获得更好的精度。告诉我你的测试值。你期望什么?这是一个n准确性问题或您的答案是否与“预期”答案完全不同?a=2 x0=1.5 n=10 100 1000 10000,则结果为1.25872.24745 2.24702 2.24698,为了获得更好的结果,您可以添加
setprecision
。以下是所有内容,效果非常好。
y=a+x-x*x;
y=(x+a/x)/2;