Newton Raphon's Method - Help
古いコメントを表示
Hello all
I'm a student and recently acquainted with MatLab, and I have to program Newton's method on it for a work.
The thing is, I'm not sure how to code it in the program.
I have the following function and values: f(x)=e^x-4x^2, with a x0?2 and a max tolerance of 0.5*10^-3. However, I have no limit for max iterations (it says "Do the necessary number of iterations" to achieve that tolerance)
Knowing that Newton's expression is x(k+1)=xk-f(x)/f'(x), I've coded the derivative of that function symbolically (in a function file, not script).
Code:
function [ y,f,f2 ] = derivf2(x)
syms t
f2=exp(t)-4.*t.^2;
f=@(t)diff(f2);
y=eval(subs(f,t,x));
end
My question is. How do I code the actual method on Matlab itself?
I've tried several times, but I ran across some problems. My intention isn't to have the exercise completely solved, but to have a general idea on how to do it to help me solve this and other exercise.
Thanks in advance
EDIT: I'm a second year college student of Chemical Engineering, I've never faced programming in my entire life until now, so please be patient with me :)
回答 (1 件)
James Tursa
2016 年 11 月 23 日
I don't know why you would use all of the symbolic stuff inside your function (as opposed to just hard coding the derivative), but here is a way to get that part of it to work:
function [ y,f,f2 ] = derivf2(x)
syms t
f2 = exp(t) - 4.*t.^2;
f = diff(f2);
y = subs(f,t,x);
end
7 件のコメント
António Aragão
2016 年 11 月 23 日
James Tursa
2016 年 11 月 23 日
編集済み: James Tursa
2016 年 11 月 23 日
Depends on how you are using this. If this is being called inside an iterative loop, why would you go through all of that symbolic stuff on each iteration? But if this is only called once at the start of your code just to get the symbolic expressions for the function and its derivative, which are then used downstream in your iterative code, then maybe this makes sense. Without seeing the rest of your code it is hard to advise.
António Aragão
2016 年 11 月 23 日
James Tursa
2016 年 11 月 23 日
編集済み: James Tursa
2016 年 11 月 23 日
Do you have the iterative stuff coded yet? (i.e., the x(k+1)=xk-f(x)/f'(x) part). Or do you need help with that?
António Aragão
2016 年 11 月 23 日
James Tursa
2016 年 11 月 23 日
編集済み: James Tursa
2016 年 11 月 23 日
OK, just piecing parts of your code together (making use of your symbolic stuff), here is a start for you:
syms t
F = exp(t) - 4*t^2
FP = diff(F)
f = str2func(['@(t)' char(F)])
fp = str2func(['@(t)' char(FP)])
x = 2
tolerance = 0.5*10^-3
%
% You need to put your iterative code here for the x = x - f(x)/fp(x) part
%
So, for the code you need to insert above, you will need to create a loop of some kind with an appropriate test condition, and inside that loop will be the "Newton expression".
António Aragão
2016 年 11 月 24 日
カテゴリ
ヘルプ センター および File Exchange で Symbolic Math Toolbox についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!