120 likes | 244 Views
Lecture 4II. fzero Multiple roots. Inline Function. fstr='x.^2-2*x-4'; fx=inline(fstr). Function evaluation. fstr='x.^2-2*x-4'; fx=inline(fstr). x = -5:1:5; y = fx(x). y = [ 31 20 11 4 -1 -4 -5 -4 -1 4 11]. >> fstr='x.^2-2*x-4'; >> fx=inline(fstr);
E N D
Lecture 4II • fzero • Multiple roots 軟體實作與計算實驗
Inline Function fstr='x.^2-2*x-4'; fx=inline(fstr) 軟體實作與計算實驗
Function evaluation fstr='x.^2-2*x-4'; fx=inline(fstr) x = -5:1:5; y = fx(x) y = [ 31 20 11 4 -1 -4 -5 -4 -1 4 11] 軟體實作與計算實驗
>> fstr='x.^2-2*x-4'; >> fx=inline(fstr); >> x=linspace(-5,5); >> plot(x,fx(x)); Plot 軟體實作與計算實驗
Find zeros >> fstr = 'x.^2-2*x-4'; >> v = fzero(fstr,1) ans = -1.2361 fx(v) ans = 0 軟體實作與計算實驗
fzero • Fzero(fstr,x0) • Input • A string of specifying a 1D function • Initial guess • Output • One root 軟體實作與計算實驗
Find multiple roots of a given function Multiple roots 軟體實作與計算實驗
Different guesses may lead to different roots >> fstr = 'x.^2-2*x-4'; >> v = fzero(fstr,1) ans = -1.2361 >> v = fzero(fstr,5) v = 3.2361 fx(v) ans = 0 fx(v) ans = 0 軟體實作與計算實驗
Flow chart v=[] for i=1:n x0=rand(1,1)*10-5; r=fzero(fstr,x0); 軟體實作與計算實驗
Flow chart v=[] for i=1:n x0=rand(1,1)*10-5; r=fzero(fstr,x0); ind = find(abs(v-r)<ep)); if length(ind) == 0 v=[v r]; end 軟體實作與計算實驗
Multiple roots source codes fstr=input('key in a function:','s'); v=[]; ep=10^-6; for i=1:10 x0=rand(1,1)*10-5; r=fzero(fstr,x0); if sum(find(abs(v-r)<ep)) == 0 v=[v r]; end end v fx=inline(fstr); x=linspace(-5,5); plot(x,fx(x));hold on; plot(v,zeros(size(v)),'ro'); 軟體實作與計算實驗