-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBinaryDivide.cpp
73 lines (59 loc) · 1.14 KB
/
BinaryDivide.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <limits>
#include <iomanip>
#include "BinaryDivide.h"
using namespace std;
//f(x)=x^3+4*x^2-10 f(x)=0的根
double binaryDivide(double a,double b,double tol){
cout << "二分法求根开始:" << endl;
double result,p,fp;
while (true){
p = (a + b) / 2.0;
fp = powf(p, 3) + 4 * powf(p, 2) - 10.0;
cout <<setprecision(16)<<"p:" << p << endl;
cout << setprecision(16)<<"fp:" << fp << endl<<endl;
if (fp == 0){
result = p;
break;
}
if (fp < 0){
a = p;
}
else{
b = p;
}
//判断精度是否足够
if (fabsf(fp) < tol){
result = p;
break;
}
}
cout << "二分法求根结束:" << endl;
return result;
}
double binaryDivide(double a, double b, double tol, double(*function)(double)){
cout << "二分法求根开始:" << endl;
double result, p, fp;
while (true){
p = (a + b) / 2.0;
fp = function(p);
cout << setprecision(16)<<"p:" << p << endl;
cout << setprecision(16)<<"fp:" << fp << endl<<endl;
if (fp == 0){
result = p;
break;
}
if (fp < 0){
a = p;
}
else{
b = p;
}
if (fabs(fp) < tol){
result = p;
break;
}
}
cout << "二分法求根结束:" << endl;
return result;
}