Convert maple code to MATLAB code

2 次查看(过去 30 天)
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

请先登录,再进行评论。

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by