具有多个 IF[] 条件的 Mathematica 函数
我这里有一段复杂的代码,既不漂亮也不容易理解,但它代表了我正在使用的大量代码的简化。我是一名 Mathematica 新手,已经从 stackoverflow 获得了有关此问题的一些帮助,但它仍然无法解决我的问题。这是我希望您能够遵循的代码并假设我正在尝试让它做什么。感谢各位编程高手的帮助。
a[b_, c_] = -3*b + 2*c + d + e + f;
g[b_, c_] := If[a[b, c] < 0, -3*a[b, c], a[b, c]];
h[T_, b_, c_] = (T/g[b, c]);
i[h_, T_, b_, c_] := If[h[T, b, c] > 0, 4*h[T, b, c], -5*h[T, b, c]];
j[b_, c_] := If[a[b, c] < 0, 5*a[b, c], 20*a[b, c]];
XYZ[h_, T_, i_, g_, j_, b_, c_] = T*i[h, T, b, c]*g[b, c] + j[b, c]
rules = {a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, T -> 10};
XYZ[h, T, i, g, j, b, c] //. rules
I have here a complicated bit of code that is not pretty nor easy to follow, but it represents a simplification of a larger body of code I am working with. I am a Mathematica novice and have already received some help on this issue from stackoverflow but it is still not solving my problem. Here is the code for which I hope you can follow along and assume what I am trying to get it to do. Thanks to you programming whizzes for the help.
a[b_, c_] = -3*b + 2*c + d + e + f;
g[b_, c_] := If[a[b, c] < 0, -3*a[b, c], a[b, c]];
h[T_, b_, c_] = (T/g[b, c]);
i[h_, T_, b_, c_] := If[h[T, b, c] > 0, 4*h[T, b, c], -5*h[T, b, c]];
j[b_, c_] := If[a[b, c] < 0, 5*a[b, c], 20*a[b, c]];
XYZ[h_, T_, i_, g_, j_, b_, c_] = T*i[h, T, b, c]*g[b, c] + j[b, c]
rules = {a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, T -> 10};
XYZ[h, T, i, g, j, b, c] //. rules
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽可能多地保留代码,只需进行一些更改即可工作:
If
语句再次外部化,如上一个问题。作为良好实践,所有定义均使用
SetDelayed
(:=
) 进行。您的
规则
中的假定错误T - 10
已更正为T -> 10
再次注意,
ReplaceRepeated
(//.
) 不再需要,改为/.
我们仍然有一个无意义的规则
a -> 1
但它不会导致失败。Preserving as much of your code as possible, it will work with just a few changes:
If
statements are again externalized, as in the last problem.all definitions are made with
SetDelayed
(:=
), as a matter of good practice.The presumed error
T - 10
in yourrules
is corrected toT -> 10
Notice that again
ReplaceRepeated
(//.
) is not needed, and is changed to/.
We still have a nonsensical rule
a -> 1
but it does not cause a failure.