newton method code with user input

2 ビュー (過去 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 Center および File ExchangePolynomials についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by