Convert maple code to MATLAB code

2 ビュー (過去 30 日間)
Juan Meza
Juan Meza 2019 年 5 月 2 日
編集済み: Walter Roberson 2019 年 5 月 2 日
Hello, I am having trouble translating Maple code to MATLAB code.
The code I am trying to translate is:
h:= 0.1;
f:= (x,y) -> 1+x^2+y;
x:= 0; y:= 1;
ans:= [x,y];
while x<1
do
F:=f(x,y); x:= x+h; y:= y+h*F;
od;
print(y); ans:= ans,[x,y];

採用された回答

Walter Roberson
Walter Roberson 2019 年 5 月 2 日
編集済み: Walter Roberson 2019 年 5 月 2 日
In MATLAB, due to finite precision, if you start with 0.1 and add 0.1 nine times, the result is slightly less than 1.
In Maple, 0.1 is represented as an sfloat, a software float, which uses a base 10 representation and so is able to represent 0.1 as exactly 1 * 10^(-1) . Adding 9 copies of that to the initial 0.1 gives you exactly 1 as a result.
Therefore the MATLAB version that madhan ravi suggests gives one more iteration than the Maple version does.
I have enclosed the translation of the Maple code to MATLAB code. There are, however, a few small differences in formatting, and I took the short-cut of implementing x^2 as x*x
It would have been a lot simpler and faster to make a minor modification to the algorithm to not add up 0.1's instead of having to implement decimal arithmetic in order to do exactly the same thing that Maple does.

その他の回答 (1 件)

madhan ravi
madhan ravi 2019 年 5 月 2 日
More or less:
h= 0.1;
f= @(x,y) 1+x.^2+y;
x= 0;
y= 1;
r = [x,y];
while x<1
F=f(x,y);
x= x+h;
y= y+h*F;
end
disp(y);
R=[x,y];
  2 件のコメント
Juan Meza
Juan Meza 2019 年 5 月 2 日
This gives the solution of 5.1878 while the textbook has the solution of 4.534344086
madhan ravi
madhan ravi 2019 年 5 月 2 日
What does maple give?

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

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by