数值计算方法:二分法求解方程的根
伪代码
fun (input x)
return x^2+x-6
newton (input a, input b, input e)
//a是区间下界,b是区间上界,e是精确度
x <- (a + b) / 2
if abs(b - 1) < e:
return x
else:
if fun(a) * fun(b) < 0:
return newton(a, x, e)
else:
return newton(x, b, e)
c/c++: 【数值计算方法(二分法求解方程的根(伪代码 python c/c++))】
#include
#include
using namespace std;
double fun (double x);
double newton (double a, double b,double e);
int main()
{
cout << newton(-5,0,0.5e-5);
return 0;
}double fun(double x)
{
return pow(x,2)+x-6;
}double newton (double a, double b, double e)
{
double x;
x = (a + b)/2;
cout << x << endl;
if ( abs(b-a) < e)
return x;
else
if (fun(a)*fun(x) < 0)
return newton(a,x,e);
else
return newton(x,b,e);
}
python:
def fun(x):
return x ** 2 + x - 6
def newton(a,b,e):
x = (a + b)/2.0
if abs(b-a) < e:
return x
else:
if fun(a) * fun(x) < 0:
return newton(a, x, e)
else:
return newton(x, b, e)
print newton(-5, 0, 5e-5)