平方根 立方根 sqrt(int m, int n) 保留n位小数 牛顿迭代法

https://leetcode-cn.com/problems/sqrtx/solution/er-fen-cha-zhao-niu-dun-fa-python-dai-ma-by-liweiw/

牛顿迭代法原理

在这里插入图片描述
利用一级泰勒级数展开式

public double mySqrt(int m, int n) {
        if (m == 0) return 0;

        double x0 = 1;
        double pre;

        while (true) {
            pre = x0;
            x0 = (x0 + m / x0) / 2;
            if (Math.abs(x0 - pre) < Math.pow(10, -n)) {
                break;
            }
        }

        BigDecimal bg = new BigDecimal(x0);
        double res = bg.setScale(n, BigDecimal.ROUND_FLOOR).doubleValue();
        return res;
    
    }
public double mySqrt3(int m, int n) {
        if (m == 0) return 0;
        int flag = 1;

        if (m < 0) {
            flag = -1;
        }

        int absM = Math.abs(m);

        double x0 = 1;
        double pre;

        while (true) {
            pre = x0;
            x0 = (2 * Math.pow(x0, 3) + absM) / (3 * Math.pow(x0, 2));
            if (Math.abs(x0 - pre) < Math.pow(10, -n)) {
                break;
            }
        }

        BigDecimal bg = new BigDecimal(x0);
        double res = bg.setScale(n, BigDecimal.ROUND_FLOOR).doubleValue();
        return res * flag;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值