Re: [運算] function 開根號

看板MATLAB作者 (RL)時間14年前 (2011/12/03 17:30), 編輯推噓1(106)
留言7則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《handsomepow (handsomepow)》之銘言: : 想請問一下 : function s = sqroot(x) [我定義sqroot(x)計算開根號的值] : b = x; : n = 1; [第一項x_0 = 1] : s = 0; : while abs(n-s) > 0.01 [我給他一個誤差] : s =(1./2).*(n+(b./n)); [題目給的疊代式x_n+1 =(1/2)*((x_n)+b/(x_n)] : n = n+1; : end : 我想寫一個算出開根號的function : 不知道是哪裡有問題 請指導一下 謝謝 %----------------------------------- function [f,g]=sqroot(x) x_n=1; temp=0; num=0; while abs(x_n-temp) > 0.01 temp=x_n; x_n=(1/2)*(temp+(x/temp)); num=num+1; end f=x_n; g=num; %---------------------------------- >>[err,itrs]=sqroot(2) err = 1.4142 itrs = 3 %---------------------------------- -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.125.38.242

12/03 17:31, , 1F
sqrt是ML內建函式
12/03 17:31, 1F
※ 編輯: Rasin 來自: 122.125.38.242 (12/03 18:14)

12/03 18:16, , 2F
謝謝r大
12/03 18:16, 2F

12/03 18:19, , 3F
但是跑不出來 0.0
12/03 18:19, 3F

12/03 18:20, , 4F
abs 那邊是不是減錯
12/03 18:20, 4F

12/03 18:22, , 5F
s要變temp
12/03 18:22, 5F
※ 編輯: Rasin 來自: 122.125.38.242 (12/03 18:24)

12/03 18:30, , 6F
err改作value
12/03 18:30, 6F

12/03 18:32, , 7F
恩恩
12/03 18:32, 7F
文章代碼(AID): #1EsUnFWU (MATLAB)
討論串 (同標題文章)
文章代碼(AID): #1EsUnFWU (MATLAB)