eval giving the wrong mathematical answer

7 ビュー (過去 30 日間)
Katie Doyle
Katie Doyle 2015 年 2 月 22 日
編集済み: John D'Errico 2015 年 2 月 22 日
I'm trying to write a script that I will use for Newton Rhapson approximation. I am testing as I go and I noticed that the eval command is returning the incorrect mathematical answer. I am testing it with x=2 with func=((2*x)*(log(x)))-1
Here is the code:
syms x;
func=input('Enter your function in terms of x: ');
f=@(x)(func);
z=diff(f(x));
f1=@(x)(z);
x0=input('Enter your initial value of x: ');
x=x0
s=char(f1);
y=subs(f1)
eval(y)
Upon entering x=2 and func=((2*x)*(log(x)))-1
The code redturns:
x =
2
y =
2*log(2) + 2
ans =
3.3863
The answer to 2*log(2)+2 should be 2.602
What am I doing wrong?

回答 (1 件)

Roger Stafford
Roger Stafford 2015 年 2 月 22 日
In matlab the 'log' function is considered to be the natural logarithm with base e, not 10. Therefore 3.3863 is the correct answer, not 2.602 .
  1 件のコメント
John D'Errico
John D'Errico 2015 年 2 月 22 日
編集済み: John D'Errico 2015 年 2 月 22 日
And of course, if you really wanted a log to the base 10, use log10.
2*log10(2)+2
ans =
2.6021
Computers are so silly. They do what you tell them to do, instead of what you want them to do.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by