论文首页哲学论文经济论文法学论文教育论文文学论文历史论文理学论文工学论文医学论文管理论文艺术论文 |
6.2 %基本二分法的C语言实现
方程式为:f(x) = 0,示例中f(x) = 1+x-x^3
使用示例:
input a b e: 1 2 1e-5
solution: 1.32472
源码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <assert.h>
double f(double x)
{
return 1+x-x*x*x;
}
int main()
{
double a = 0, b = 0, e = 1e-5;
printf("input a b e: ");
scanf("%lf%lf%lf", &a, &b, &e);
e = fabs(e);
if (fabs(f(a)) <= e)
{
printf("solution: %lg\n", a);
}
else if (fabs(f(b)) <= e)
{
printf("solution: %lg\n", b);
}
else if (f(a)*f(b) > 0)
{
printf("f(%lg)*f(%lg) > 0 ! need <= 0 !\n", a, b);
}
else
{
while (fabs(b-a) > e) (转载自http://zw.nseac.coM科教作文网)
{
double c = (a+b)/2.0;
if (f(a)* f ( c ) < 0)
b = c;
else
a = c;
}
printf("solution: %lg\n", (a+b)/2.0);