While Loop code not working?

3 ビュー (過去 30 日間)
Bob
Bob 2015 年 2 月 17 日
コメント済み: Bob 2015 年 2 月 18 日
Question: I have to create a function m file called myfirstzero(f,a) which takes two inputs:
f: A function handle which you may assume will represent a polynomial.
a: A real number.
Does: Uses a while loop to find the smallest n such f(n)(a) = 0. Note that this means the nth derivative at x = a and note that n = 0 is fair game, where the 0th derivative of a function is just the function itself.
Returns: This value of n.
This is my code:
function a = myfirstzero(f,a)
syms x;
n = 0;
d = abs(subs(f(x),a));
while (d > 0);
d = subs(diff(f(x),n),a);
n = n+1;
end
a = n;
end
Testing: When I test the code with results =myfirstzero(@(x) x^3+2,0) I get a= 2 when the correct answer should actually be 1.
Can someone help me with fine tuning my code. It works with some of my test data but not all of it. Below is all the test data I have to test this code:
a = myfirstzero(@(x) 2*x^3-3*x^2-12*x+6,2)----> works
a =1
a = myfirstzero(@(x) x^3,0)----->works
a =0
a = myfirstzero(@(x) x^3+2,0)----> not work
a =1
a = myfirstzero(@(x) x^6-5*x^5-2*x^4-x^3+x^2-x+10,3)---->not work
a =7
a = myfirstzero(@(x) x^5-x^3,2)----->not work
a =6
a = myfirstzero(@(x) x^4-10*x^3+24*x^2,1)----->not work
a =2
Test data file is also attached.

回答 (2 件)

Bob
Bob 2015 年 2 月 18 日
Can anyone help me?
  2 件のコメント
Erik S.
Erik S. 2015 年 2 月 18 日
Don't see your test data file
Bob
Bob 2015 年 2 月 18 日
編集済み: Bob 2015 年 2 月 18 日
Sorry forgot to attach but here. It is also included in my question.

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


Claire Li
Claire Li 2015 年 2 月 18 日
For the first test data sample that doesnt work for you, it seemed like it was because it doesn't know to stop when n=1 because its also 0 when n=2?
Try adding a break somewhere
  1 件のコメント
Bob
Bob 2015 年 2 月 18 日
Adding the break gave me a different answer, that was still wrong.

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

カテゴリ

Help Center および File ExchangeMATLAB についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by