Find the square root of the number without using any built-in function?











up vote
0
down vote

favorite












I am working on below problem:




Given an integer, how do you find the square root of the number
without using any built-in function?




  private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);

while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}


I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?










share|improve this question






















  • If you can use Math.abs(), then why not also use Math.sqrt()?
    – 200_success
    2 days ago










  • Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
    – Calak
    2 days ago










  • a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
    – Martin Frank
    2 days ago















up vote
0
down vote

favorite












I am working on below problem:




Given an integer, how do you find the square root of the number
without using any built-in function?




  private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);

while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}


I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?










share|improve this question






















  • If you can use Math.abs(), then why not also use Math.sqrt()?
    – 200_success
    2 days ago










  • Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
    – Calak
    2 days ago










  • a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
    – Martin Frank
    2 days ago













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am working on below problem:




Given an integer, how do you find the square root of the number
without using any built-in function?




  private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);

while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}


I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?










share|improve this question













I am working on below problem:




Given an integer, how do you find the square root of the number
without using any built-in function?




  private static double computeSquareRootBinarySearch(double x, double precision) {
double start = 0;
double end = x / 2 + 1;
double mid = (start + ((end - start) / 2));
double prevMid = 0;
double diff = Math.abs(mid - prevMid);

while ((mid * mid != x) && (diff > precision)) {
if (mid * mid > x) {
end = mid;
} else {
start = mid;
}
prevMid = mid;
mid = (start + end) / 2;
diff = Math.abs(mid - prevMid);
}
return mid;
}


I came up with above binary search algo but wanted to see if there is any optimization I can do in above algorithm?







java binary-search






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









user5447339

13817




13817












  • If you can use Math.abs(), then why not also use Math.sqrt()?
    – 200_success
    2 days ago










  • Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
    – Calak
    2 days ago










  • a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
    – Martin Frank
    2 days ago


















  • If you can use Math.abs(), then why not also use Math.sqrt()?
    – 200_success
    2 days ago










  • Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
    – Calak
    2 days ago










  • a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
    – Martin Frank
    2 days ago
















If you can use Math.abs(), then why not also use Math.sqrt()?
– 200_success
2 days ago




If you can use Math.abs(), then why not also use Math.sqrt()?
– 200_success
2 days ago












Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
– Calak
2 days ago




Agree with @200_success, try to compute the Abs(...) by yourself. Otherwise, why theses operations in the mid and diff initialization? And, it's not stated that the result must be the closest greater possible. So, why + 1 in the end init?
– Calak
2 days ago












a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
– Martin Frank
2 days ago




a really efficent way to calculate approximations would be to use the Secant method (see en.wikipedia.org/wiki/Secant_method)
– Martin Frank
2 days ago










1 Answer
1






active

oldest

votes

















up vote
2
down vote














  • It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.


  • The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.


  • As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.


  • You may want to check the input for correctness: both x and precision must be positive.







share|improve this answer





















    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207592%2ffind-the-square-root-of-the-number-without-using-any-built-in-function%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote














    • It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.


    • The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.


    • As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.


    • You may want to check the input for correctness: both x and precision must be positive.







    share|improve this answer

























      up vote
      2
      down vote














      • It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.


      • The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.


      • As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.


      • You may want to check the input for correctness: both x and precision must be positive.







      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote










        • It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.


        • The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.


        • As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.


        • You may want to check the input for correctness: both x and precision must be positive.







        share|improve this answer













        • It is unlikely that mid * mid would ever be equal to x, so the opportunistic mid * mid != x consumes more cycles than it may save. I recommend to drop it entirely.


        • The convergence rate is not the best. Your algorithm adds (approximately) one bit of precision per iteration. Compare it to a classic Newton-Raphson, which doubles the amount of correct bits per iteration.


        • As mentioned in the comment, without using any built-in function part of assignment rules out using Math.abs.


        • You may want to check the input for correctness: both x and precision must be positive.








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        vnp

        38.1k13096




        38.1k13096






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207592%2ffind-the-square-root-of-the-number-without-using-any-built-in-function%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Morgemoulin

            Scott Moir

            Souastre