欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

大数据分析技术之qrt(x)II

程序员文章站 2022-07-28 21:01:35
Implementdouble sqrt(double x)andx >= 0. Compute and return the square root of x. Not...

Implementdouble sqrt(double x)andx >= 0.

Compute and return the square root of x.

Notice

You do not care about the accuracy of the result, we will help you to output results.

Have you met this question in a real interview? Yes Example

Givenn=2return1.41421356

计算时,需要注意小数的计算,当开方的数是小数时,将end的默认值定义为0;

 

java

public class Solution {
    /*
     * @param x: a double
     * @return: the square root of x
     */
    public double sqrt(double x) {
        // write your code here
        if (x < 0) {
            return -1;
        }
        double start = 0;
        double end = x;
        if (end < 1) {
            end = 1;
        }
        double mid = 0;
        double eps = 1e-12;
        while (end - start > eps) {
            mid = (end - start) / 2 + start;
            if (mid * mid > x) {
                end = mid;
            } else {
                start = mid;
            }
        }
        return start;
    }
}