自己動手實現C標准庫中sqrt()函數


今天在C和指針P63看到了這個計算公式,ai+1 = ( ai + number/ai ) / 2。之前也有在網上看到過,不過出處忘了,記得好像是關於組合數學還是數論里面的一個內容。

 

公式很簡單,理論這個我就不懂了,還希望各位給指導一下。下面貼出自己的代碼,作為記憶保留。

 1 float my_sqrt(float number) {
 2     float new_guess;
 3     float last_guess;
 4     
 5     if (number < 0) {
 6         printf("Cannot compute the square root of a negative number!\n");
 7         return -1;
 8     }
 9     
10     new_guess = 1;
11     do {
12         last_guess = new_guess;
13         new_guess = (last_guess + number / last_guess) / 2;
14         printf("%.15e\n", new_guess);
15     } while (new_guess != last_guess);
16     
17     return new_guess;
18 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM