求平方根的4种方法

求平方根一共有四种方法,袖珍计算器法、浮点二分法、牛顿法和梯度下降法,具体思路清查阅参考资料。代码如下:

#include <iostream>
#include <algorithm>
#include <cmath>


using namespace std;


using ld = long double;

ld eps = 1e-8;

// 袖珍计算器方法
ld func_1(ld x) {
    return exp(0.5 * log(x));
}

// 浮点二分
ld func_2(ld x) {
    ld l = 0, r = max(ld(1), x), m;
    while (r - l >= eps) {
        m = (l + r) / 2;
        if (m * m < x)
            l = m;
        else
            r = m;
    }
    return l;
}

// 牛顿法
ld func_3(ld x) {
    ld x0 = x;
    while (fabs(x0 * x0 - x) >= eps) {
        ld fx0 = x0 * x0 - x;
        x0 = x0 - fx0 / (2 * x0);
    }
    return x0;
}

// 梯度下降法
ld func_4(ld x, ld lr) {
    ld x0 = x;
    while (fabs(x0 * x0 - x) >= eps) {
        x0 = x0 - lr * 4 * x0 * (x0 * x0 - x);
    }
    return x0;
}


int main() {
    ld x;
    cin >> x;
    cout << func_1(x) << endl;
    cout << func_2(x) << endl;
    cout << func_3(x) << endl;
    cout << func_4(x, 0.01) << endl;

    return 0;
}

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值