Square root in C using Newton-Raphson method

后端 未结 4 697
一向
一向 2021-01-16 10:08

In the following code, I want to replace the termination condition to: if the ratio of guess square and x is close to 1, while loop should terminate. I tried various express

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-16 10:55

    It's possible you can't reach that guess*guess will be enough close to x; imagine e.g. sqrt of 2e38 - every approximation will be no closer than ~1e31 and your exit condition won't ever succeed.

    The variant good for all cases is that stopping for this method occur when guess stops to change. So you would write something like

    prev_guess = 0; // any initial value is ok
    while (guess != prev_guess) {
        ...
        prev_guess = guess;
    }
    

    at least it shall work for any IEEE754-compatible implementation not reaching overflow or underflow.

    Also you can compare guess and prev_guess for difference (as soon as the goal is usually to match enough accuracy of root, not the value squared back).

提交回复
热议问题