二元搜索解优化问题

    科技2022-08-09  124

    #include <stdio.h> //binSearch计算x^2=2的近似解,精度1e-5; 证明二元搜索的快速低复杂度寻优能力 float func(float x) { return x * x - 2; } float binSearch(float beg, float end, float acc) { float mid; while ( end - beg > acc) { mid = (end + beg) / 2; if (func(mid) > 0) { //递增是大于,否者相反 end = mid; } else { beg = mid; } printf("beg,end,acc %f,%f,%f\n",beg,end,acc); } return mid; } int main () { float a = binSearch(1, 2, 1e-5); printf("x*x = 2 solution is %f\n", a); //binSearch(1, 2, 1e-2) printf("x*x = 2 solution is %f\n", binSearch(1, 2, 1e-6)); printf("x*x = 2 solution is %f\n", binSearch(1, 2, 1e-10)); //1e-10明显超出float精度了,造成算法不收敛; return 0; } 圆剖面,倒水之后水面下和总半圆面积比值r(0.6比如),问灌水高度多少;转为优化问题 灌水高度h介于[0,R]之间优化;
    Processed: 0.011, SQL: 8