你能提出什么问题吗?[0;2]在具有精度的段上0.5,程序应该输出近似0.9,但在这种情况下它输出1.8。
#include <stdio.h>
#include <math.h>
double f(double x) {
return (x*x*x - 3.0*x);
}
double ternar(double a, double b, double eps) {
double l, r, mr, ml;
r = b;
l = a;
while (fabs(r - l) > eps) {
ml = l + (r - l)/3.0;
mr = r - (r - l)/3.0;
if(f(ml) < f(mr))
l = ml;
else
r = mr;
}
return (l+r)/2.0;
}
int main () {
double a, b, eps;
puts("a b eps");
scanf ("%lf %lf %lf", &a, &b, &eps);
printf ("Ternar: %lf\n", ternar(a, b, eps));
}
在你的功能搜索最大值。为了使其搜索最小值,您需要将其修复为
f(ml) > f(mr). 您可以编写一个通用版本:找到最小值/最大值:
或更简单,没有乘法: