如何在 Mathematica 中编写欧拉函数?
我编写了一个欧拉函数,但读错了指令,所以现在我必须创建一个新函数,但我无法弄清楚。
我制作了以下自动欧拉函数。
f[x_, y_] := -x y^2;
x0 = 0;
y0 = 2;
xend = 2;
steps = 20;
h = (xend - x0)/steps // N;
x = x0;
y = y0;
eulerlist = {{x, y}};
For[i = 1, i <= steps, y = f[x, y]*h + y;
x = x + h;
eulerlist = Append[eulerlist, {x, y}];
i++
]
Print[eulerlist]
但它只是生成我指定的列表。
我想要一个能够生成这种形式的欧拉函数:
Euler[y, 2, -x y^2, {x, 0, 2}, 20]
我似乎没有进一步了解。
I programmed a Euler function but misread the instructions, so now I have to make a new one, but I can't figure it out.
I have made the following automatic Euler function.
f[x_, y_] := -x y^2;
x0 = 0;
y0 = 2;
xend = 2;
steps = 20;
h = (xend - x0)/steps // N;
x = x0;
y = y0;
eulerlist = {{x, y}};
For[i = 1, i <= steps, y = f[x, y]*h + y;
x = x + h;
eulerlist = Append[eulerlist, {x, y}];
i++
]
Print[eulerlist]
But it just generates the list I have specified.
I would like to have a Euler function which is able to generate this form:
Euler[y, 2, -x y^2, {x, 0, 2}, 20]
I don't seem to get any further.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前尚不清楚您在问什么,但如果您想要的是能够输入
并获取
那么您需要编写如下函数定义:
注意下划线表示模式,即
:=
表示延迟评估和模式规范Integer?Positive
。至于函数体——天哪,你能选择一种不那么 Mathematica 风格的方法吗?也许不是。过程循环和 Append 几乎从来都不是在 Mathematica 中执行任何操作的最佳方式。
这是一个更好的解决方案。
如果您想要输出
Euler[y, 2, -xy^2, {x, 0, 2}, 20]
,那么将其输入到笔记本中就是最快的方法。It is not clear what you are asking, but if what you want is to be able to input
and get
Then you need to write a function definition like this:
Notice the underscores to denote patterns, the
:=
to denote delayed evaluation and the pattern specificationInteger?Positive
.As for the body of the function -- oh my goodness could you have picked a less Mathematica-style approach? Perhaps not. Procedural loops and
Append
are almost never the best way to do anything in Mathematica.Here is a better solution.
If you want something that outputs
Euler[y, 2, -x y^2, {x, 0, 2}, 20]
, then typing it into the notebook is the quickest method.