フィルターのクリア

Function Intersection using Newton's Method

5 ビュー (過去 30 日間)
SB
SB 2012 年 11 月 19 日
編集済み: Torsten 2022 年 11 月 27 日
Hi everyone, I'm trying to write a function that finds a point at
which two functions f(x) and g(x) intersect, i.e., f(x) = g(x). I'm using
Newton's Method and making and h(x)=f(x)-g(x) and h'(x) as well, but I'm not getting the right x-value. Please help me debug my code!
% function x = fgIntersect(f, df, g, dg, x0, tol, maxIter)
h=f(x0)-g(x0)
dh=df(x0)-dg(x0)
k=1;
while k<=maxIter
x=x0-h/dh;
if abs(x-x0)<tol*abs(x)
return
end
x0=x;
k=k+1;
end
end
  2 件のコメント
Matt J
Matt J 2012 年 11 月 19 日
Give us example data that let's us reproduce the failure.
SB
SB 2012 年 11 月 19 日
編集済み: SB 2012 年 11 月 19 日
format compact; format long;
f = @(x) exp(x) - 3;
df = @(x) exp(x);
g = @(x) sqrt(x);
dg = @(x) .5*x^(-.5);
x = fgIntersect(f, df, g, dg, 1, 1e-6, 50)
x should equal 1.434542442506692
Another case:
format compact; format long;
p1 = [1 -2 3 -8];
p2 = [1 -3 2 -4];
f = @(x) polyval(p1,x);
df = @(x) polyval(polyder(p1),x);
g = @(x) polyval(p2,x);
dg = @(x) polyval(polyder(p2),x);
x = fgIntersect(f, df, g, dg, 2, 1e-6, 50)
x should be 1.561552842846145

サインインしてコメントする。

採用された回答

Matt J
Matt J 2012 年 11 月 19 日
You're not updating h and dh within your loop.
  4 件のコメント
SB
SB 2012 年 11 月 19 日
Thank you so much! I got it, I can't believe I forgot to update them within my loop.
Torsten
Torsten 2022 年 11 月 26 日
編集済み: Torsten 2022 年 11 月 27 日
f = @(x) exp(x) - 3;
df = @(x) exp(x);
g = @(x) sqrt(x);
dg = @(x) .5*x^(-.5);
x = fgIntersect(f, df, g, dg, 1, 1e-6, 50)
x = 1.4345
p1 = [1 -2 3 -8];
p2 = [1 -3 2 -4];
f = @(x) polyval(p1,x);
df = @(x) polyval(polyder(p1),x);
g = @(x) polyval(p2,x);
dg = @(x) polyval(polyder(p2),x);
x = fgIntersect(f, df, g, dg, 2, 1e-6, 50)
x = 1.5616
function x = fgIntersect(f, df, g, dg, x0, tol, maxIter)
h=f(x0)-g(x0);
dh=df(x0)-dg(x0);
k=1;
while k<=maxIter
x=x0-h/dh;
if abs(x-x0)<tol*abs(x)
return
end
x0=x;
h = f(x0)-g(x0);
dh = df(x0)-dg(x0);
k=k+1;
end
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStatistics and Machine Learning Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by