标签:info ble 精度 mamicode int double while ima alt
#include <stdio.h> #include <math.h> double a, b;//定义全局变量,传递区间值,可尝试指针 double get_num(double m) { double f; f = m * m + 7 * m - 9; return f; } double search_num(double x1, double h) { double x2, x3; double y1, y2, y3; x2 = x1 + h; y1 = get_num(x1); y2 = get_num(x2); //递减区间 if (y1 > y2) { h = 2 * h; x3 = x2 + h; y3 = get_num(x3); if (y2 > y3) { h = h; while (!(y2 < y3)) { x1 = x2; y1 = y2; x2 = x3; y2 = y3; x3 = x2 + h; y3 = get_num(x3); } } printf("区间为:[%.3f,%.3f]\n", x1, x3); a = x1; b = x3; printf("%.3f,%.3f,%.3f\n", y1, y2, y3); } //递增区间,反向搜索 if (y1 < y2) { double temp; temp = x1; x1 = x2; y1 = y2; x2 = temp; y2 = get_num(x2); x3 = x2 - 2 * h; y3 = get_num(x3); if (y2 > y3) { while (!(y2 < y3)) { x1 = x2; y1 = y2; x2 = x3; y2 = y3; x3 = x2 - h; y3 = get_num(x3); } } printf("区间为:[%.3f,%.3f]\n", x1, x3); a = x1; b = x3; printf("%.3f,%.3f,%.3f\n", y1, y2, y3); } return a,b; } void fen_ge(double m, double n) { double s = 0.618; double m1, n1; double y1, y2; double temp; double q = 0.1;//定义精度 m1 = n - s * (n - m); n1 = m + s * (n - a); y1 = get_num(m1); y2 = get_num(n1); while (1) { if (y1 >= y2) { m = m1; m1 = n - s*(n - m); n1 = m + s*(n - m); y1 = get_num(m1); y2 = get_num(n1); } else { n = n1; m1 = n - s*(n - m); n1 = m + s*(n - m); y1 = get_num(m1); y2 = get_num(n1); } temp = (double)abs(n - m); if (temp < q) { printf("%f,%f\n,%f,%f\n", m, n, y1, y2); break; } } return 0; } void main() { search_num(10.0, 0.5); fen_ge(a, b); return 0; }
输出结果如下:
标签:info ble 精度 mamicode int double while ima alt
原文地址:https://www.cnblogs.com/hspzm/p/14063124.html