newton method code with user input

10 次查看(过去 30 天)
sina roshanaei
sina roshanaei 2016-2-29
编辑: Ced 2016-3-6
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 个评论
Ced
Ced 2016-3-6
编辑:Ced 2016-3-6
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

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Polynomials 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by