大数据分析技术之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)and
x >= 0.
Compute and return the square root of x.
Notice
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
Given
n=
2return
1.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; } }
上一篇: python实现随机梯度下降(SGD)