c++中的牛顿方法
Newtons method in C++
嗨,我已经检查了许多其他问题,但似乎无法弄清楚为什么我的实现不会收敛。我一直得到"错误,没有收敛"的部分,我的程序,甚至当我进入根。
函数y = x^2 - 1
代码如下:
// Newton sqaure root finder function
#include <iostream>
#include <cmath>
int main()
{
using namespace std;
// Enter an initial guess x
cout << "Enter an initial guess: ";
double x;
cin >> x;
// Define & initialize the error, tolerance and iteration variables
double tol = 1e-12;
cout << 1e-12;
double error = tol + 1;
int it = 0;
int max_it = 100;
// Define the x1 variable to hold the latest result (root approximation)
double x1;
// Start while loop with guess x to find the root
while (error > tol && it < max_it)
{
x1 = x + (x*x-1) / (2*x);
error = fabs(x1 - x);
x = x1;
it++;
cout << error << endl;
}
if (error <= tol)
{
cout << "The root is " << x << endl;
}
else
{
cout << "Error, no convergence" << endl;
}
cin.get();
cin.get();
return 0;
}
你的公式中有一个打字错误
x1 = x + (x*x-1) / (2*x);
应该是
x1 = x - (x*x-1) / (2*x);
你可以在这里看到:https://en.wikipedia.org/wiki/Methods_of_computing_square_roots
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 通过方法访问结构
- 最小硬币更换问题(自上而下方法)
- C++为构建时间获取QDateTime的可靠方法
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 有什么方法可以遍历结构吗
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 使用std::函数映射对象方法
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- C++从另一个类访问公共静态向量的正确方法是什么
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 没有为自己的结构调用列表推回方法
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 枚举环境变量的惯用C++14/C++17方法
- 初始化具有非默认构造函数的std::数组项的更好方法