美文网首页
单调函数的零点问题(模板)

单调函数的零点问题(模板)

作者: km15 | 来源:发表于2020-02-04 18:34 被阅读0次

learn && wrong:

1、f(mid)与2的关系,改成与o的关系
2、f(x)更改一下
3、如果递减,只需要把f(mid)改成小于号

#include <iostream>

const double eps = 1e-5; //精度为10的-5次方(!!!)

double f(double x) {  //计算f(x)
    return ...
}

double calsqrt() {
    double left = 1, right = 2, mid; //[left,right] = [1,2]
    while (right - left > eps) {
        mid = (right - left) / 2;
        if (f(mid) > 0) {
            right = mid;
        }
        else if(f(mid) < 0) {
            left = mid;
        }
    }
    return mid;
}
#include <iostream>

const double eps = 1e-5; //精度为10的-5次方(!!!)

double f(double x) {  //计算f(x)
    return x * x;
}

double calsqrt() {
    double left = 1, right = 2, mid; //[left,right] = [1,2]
    while (right - left > eps) {
        mid = (right - left) / 2;
        if (f(mid) > 2) {
            right = mid;
        }
        else if(f(mid) < 2) {
            left = mid;
        }
    }
    return mid;
}

相关文章

网友评论

      本文标题:单调函数的零点问题(模板)

      本文链接:https://www.haomeiwen.com/subject/faghxhtx.html