newton method code with user input
2 views (last 30 days)
Show older comments
HI, I have simple problem, Iam trying to use newton's method with the code below. However since my polynomial is always going to be in fourth order I wish to make it a user input method to make it easier for myself rather than having to write the 100+ polynomials.
% code
function p=test(x)
a1=input('Type a1 value: \n');
a2=input('Type a2 value: \n');
a3=input('Type a3 value: \n');
a4=input('Type a4 value: \n');
p=1+a1*x+a2*x^2+a3*x^3+a4*x^4;
z=diff(f(x));
f1=inline(z);
x0=input('Guess the number= \n');
x=x0
for u=0:inf
y=x
x=y-(f(x)/f1(x));
if x==y
break
end
end
I will greatly appreciate your help.
thanks
1 Comment
Ced
on 6 Mar 2016
Edited: Ced
on 6 Mar 2016
I am not sure I understand the question. Why would you have to write 100+ polynomials? Why not just pass the coefficients as a input parameter to your function, i.e.
function p = test(x,a)
% a = [ a0 a1 a2 a3 a4 ]
p = x.^(0:5)*a(:); % this does 1*a0 + x*a1 + ... + x^4*a4
...
Otherwise, you can also pass a complete vector with input:
a = input('Type the coefficient vector [ a0 a1 a2 a3 a4 ]\n');
Then, minor comments:
1. I would recommend using a finite maximum number of iterations instead of inf.
2. You will probably want to check (abs(x-y) < small_number) instead of x == y since this is a numerical algorithm.
PS: You might want to have a look at polyval if you want to use inbuilt matlab functions with polynomials
Answers (0)
See Also
Categories
Find more on Polynomials in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!