[討論] 牛頓法的求值與繪圖問題>"<

看板MATLAB作者 (成人展三萬嫖妓)時間14年前 (2011/11/15 11:03), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/1
是這樣的>"< 這個問題是老師後天考試前發下來 給大家作為範例參考的題目 如下: ================================================================ Newton's method is an efficient algorithm for finding approximations to the zeros (or roots) of a real-valued function. The algorithm can be written as follows Xn+1 = Xn - [f(Xn) / f'(Xn)] Newton’s method iteratively approximates the root(s) for function f(x) until Xn+1 and Xn difference is smaller than real number e for example |Xn+1 - Xn| <e (e沒給 我自設 1e-4) write a script that that performs the Newton method to find a root for y = xn^3 - 5*xn^2 - xn + 5 Plot the Xn on the y-axis with number of iterations on the x-axis. =========================================================== 目前我寫成這樣: xn = input('first x?\n'); y = xn^3 - 5*xn^2 - xn + 5; yplum = 3*xn^2 - 10*xn - 1; cnt = 1; e = 1e-4; while cnt<=10000; xn1 = xn - y / yplum if abs(xn1 - xn)<= e fprintf('converged') break; end xn = xn1 cnt = cnt + 1 end =========================================================== 問一下這樣是對的嗎? xn = -1.6062e+005 這答案是對的嗎? 我起始x = 50 xn = -2.9412e+005 起始x = 90 xn = -4.9415e+005 起始x= 150 跑幾次都不一樣>< 另外畫圖要怎麼畫? 跪求~感謝>< 那時候作業有個神人教我用clf hold figure等 現在我又不會用了....當時畫出來的都跟同學不一樣>< -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.76.121

11/15 12:59, , 1F
迴圈很有問題 自己想像模擬一下馬上就會看出來了
11/15 12:59, 1F

11/15 13:00, , 2F
你在迴圈裡沒有重新計算xn,y,yplum 跑再多次都一樣
11/15 13:00, 2F

11/15 13:00, , 3F
然後記得每一行結尾要加 ;
11/15 13:00, 3F

11/15 15:03, , 4F
感謝大大。目前解答改成
11/15 15:03, 4F
xn = input('first x?\n'); cnt = 1; e = 1e-4; while cnt<=10000; y = xn^3 - 5*xn^2 - xn + 5; yplum = 3*xn^2 - 10*xn - 1; xn1 = xn - y / yplum if abs(xn1 - xn)<= e fprintf('converged') break; end xn = xn1 cnt = cnt + 1 end 預祝大大事事順利 ※ 編輯: gfs777 來自: 140.112.183.66 (11/15 15:04)
文章代碼(AID): #1EmTQCpu (MATLAB)
文章代碼(AID): #1EmTQCpu (MATLAB)