问题引入
编写程序,分别用二分法和牛顿迭代法求解方程x3 – 3x – 1 = 0在x = 2附近的实根,要求计算精确到小数点后7 位数字为止,并将求出的近似结果与理论值2cos20 比较误差大小。
设二分法的初始迭代区间为 [1, 3],牛顿迭代法的起点为4。
二分法
任取两点x1和x2,判断(x1,x2)区间内有无一个实根。如果f(x1)和f(x2)符号相反,说明(x1,x2)之间有一个实根。取(x1,x2)的中点x,检查f(x)与f(x1)是否同符号,如果不同号,说明实根在(x,x1)区间,这样就已经将寻找根的范围减少了一半了。
然后用同样的办法再进一步缩小范围。再找x1与x2(x2=x)的中点“x”,并且再舍弃其一半区间。如果f(x)与f(x1)同号,则说明根在(x,x2)区间,再取x与x2的中点,并舍弃其一半区间。用这个办法不断缩小范围,直到区间相当小为止。
//二分法近似
bool Dichotomy() {
double max = 3;
double min = 1;
double mid = (max + min) / 2;
if (func(mid) == 0) {
;
}
else {
while (abs(func(mid)) > p) {//int abs(int i);返回整型参数i的绝对值,用来判断精度是否达到要求
if (func(mid) * func(min) > 0) {
min = mid;
}
else {
max = mid;
}
mid = (max + min) / 2;
}
}
cout << "二分法近似结果:" <<setprecision(8) <<mid << endl;
return true;
}
牛顿迭代法
用牛顿迭代法求f(x)方法
1
用一个与原方程的近似方程,去求解近似根appro;
2
再通过x1求出f(x1)
3
用切线公式destination = iter - actual / appro使最终结果逐渐逼近原根。
在几何上就是作线x=x1,交f(x)于f(x1);
过f(x1)作f(x)的切线,交x轴于x2。可以用公式求出x2,通过x2求出f(x2);…一直求下去,直到接近真正的根。当两次求出的根之差|xn+1-xn|≤ε就认为 xn+1足够接近于真实根。
//牛顿法近似
bool Newton() {
double appro, actual, iter, destination = 4;
do {
iter = destination;
appro = 3 * iter * iter - 3;//近似方程
actual = iter * iter * iter - 3 * iter - 1;//实际方程
destination = iter - actual / appro;//用最终结果去减两个方程的商,逐渐迭代
} while (abs(iter - destination) > p);
cout<<"牛顿法近似结果:"<< setprecision(8)<< destination<<endl;
return true;
}
时空复杂度分析
二分法:
算法为一重循环,循环次数和精度有关; 空间上只占用了三个临时变量为常数阶。
时间复杂度为O(n),空间复杂度为O(1)。
牛顿迭代法:
算法也为一重循环,循环次数和精度有关; 空间上占用了四个临时变量为常数阶。
时间复杂度为O(n),空间复杂度为O(1)。
附录–完整代码块
#include<iostream>
#include<cmath>
#include<iomanip>
#define PI 3.1415926 //假定PI值
using namespace std;
//用来精确7位小数
double p = 1e-7;
//二分法近似的方程表达式
double func(double x)
{
return x * x * x - 3 * x - 1;
}
//二分法近似
bool Dichotomy() {
double max = 3;
double min = 1;
double mid = (max + min) / 2;
if (func(mid) == 0) {
;
}
else {
while (abs(func(mid)) > p) {//int abs(int i);返回整型参数i的绝对值,用来判断精度是否达到要求
if (func(mid) * func(min) > 0) {
min = mid;
}
else {
max = mid;
}
mid = (max + min) / 2;
}
}
cout << "二分法近似结果:" <<setprecision(8) <<mid << endl;
return true;
}
//牛顿法近似
bool Newton() {
double appro, actual, iter, destination = 4;
do {
iter = destination;
appro = 3 * iter * iter - 3;//近似方程
actual = iter * iter * iter - 3 * iter - 1;//实际方程
destination = iter - actual / appro;//用最终结果去减两个方程的商,逐渐迭代
} while (abs(iter - destination) > p);
cout<<"牛顿法近似结果:"<< setprecision(8)<< destination<<endl;
return true;
}
int main() {
cout<<"2cos20 " <<" = " << setprecision(8) << 2 * cos(PI / 9)<<endl;//注意cos的传入值是弧度制
Dichotomy();
Newton();
return 0;
}