javascript怎么实现验证码(求sqrt平方根的三种方法)

javascript怎么实现验证码(求sqrt平方根的三种方法)(1)

总结求平方根sqrt的三种方法,首先是牛顿迭代法:

function abs(x) { return x >= 0 ? x : -x; } function square(x) { return x * x; } function good_enough(guess, x) { return abs(square(guess) - x) < 0.001; } function average(x, y) { return (x y) / 2; } function improve(guess, x) { return average(guess, x / guess); } function sqrt_iter(guess, x) { return good_enough(guess, x) ? guess : sqrt_iter(improve(guess, x), x); } function sqrt(x) { return sqrt_iter(1, x); } sqrt(5); > 2.2360688956433634

其次是二分法:

function average(x, y) { return (x y) / 2; } function positive(x) { return x > 0; } function negative(x) { return x < 0; } function abs(x) { return x >= 0 ? x : -x; } function close_enough(x, y) { return abs(x - y) < 0.001; } function search(f, neg_point, pos_point) { let midpoint = average(neg_point, pos_point); if (close_enough(neg_point, pos_point)) { return midpoint; } else { let test_value = f(midpoint); if (positive(test_value)) { return search(f, neg_point, midpoint); } else if (negative(test_value)) { return search(f, midpoint, pos_point); } else { return midpoint; } } } function binary_search_method(f, a, b) { let a_value = f(a); let b_value = f(b); return negative(a_value) && positive(b_value) ? search(f, a, b) : negative(b_value) && positive(a_value) ? search(f, b, a) : error("values are not of opposite sign"); } console.log(binary_search_method(x => x ** 2 - 5, 0, 5)); > 2.23602294921875

最后是“不动点方程”:

function abs(x) { return x >= 0 ? x : -x; } const tolerance = 0.00001; function fixed_point(f, first_guess) { function close_enough(x, y) { return abs(x - y) < tolerance; } function try_with(guess) { const next = f(guess); return close_enough(guess, next) ? next : try_with(next); } return try_with(first_guess); } function average(x, y) { return (x y) / 2; } function sqrt(x) { return fixed_point(y => average(y, x / y), 1); } sqrt(5);

以上为三种求“平方根”的方法。

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页