Mathematica 中奇怪的替换行为

发布于 2024-08-26 05:25:29 字数 528 浏览 10 评论 0原文

我的问题是:为什么以下不起作用,我该如何修复它?

Plot[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

结果是两个空白图表。通过比较,

DummyFunction[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

给出

{DummyFunction[Sin[t], {t, 0, 2 *Pi}],  DummyFunction[Cos[t], {t, 0, 2 * Pi}]}

所需的结果。

这是我实际所做的事情的简化版本。我非常恼火的是,即使在找出了放置大括号的烦人的“正确方法”之后也没有任何作用。

最后,我做了以下工作,效果很好:

p[f_] := Plot[f[t], {t, 0, 2*Pi}]
p[Sin]
p[Cos]

My question is: why doesn't the following work, and how do I fix it?

Plot[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

The result is two blank graphs. By comparison,

DummyFunction[f[t], {t, 0, 2*Pi}] /. {{f -> Sin}, {f -> Cos}}

gives

{DummyFunction[Sin[t], {t, 0, 2 *Pi}],  DummyFunction[Cos[t], {t, 0, 2 * Pi}]}

as desired.

This is a simplified version of what I was actually doing. I was very annoyed that, even after figuring out the annoying "right way" of putting the curly brackets nothing works.

In the end, I did the following, which works:

p[f_] := Plot[f[t], {t, 0, 2*Pi}]
p[Sin]
p[Cos]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

德意的啸 2024-09-02 05:25:29

作为 Peter 的 Hold/ReleaseHold 策略的替代方案,您可以这样做,

Plot[Evaluate[ f[t]/. {{f -> Sin}, {f -> Cos}} ], {t, 0, 2*Pi}]

这样读起来更清晰。这可确保在计算 Plot 之前替换 f

As an alternative to Peter's Hold/ReleaseHold strategy you could do

Plot[Evaluate[ f[t]/. {{f -> Sin}, {f -> Cos}} ], {t, 0, 2*Pi}]

which is a little cleaner to read. This ensures that f is substituted before Plot is evaluated.

橘香 2024-09-02 05:25:29

这个甚至更短:

Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos}

This one is even shorter:

Plot[#[t], {t, 0, 2*Pi}] & /@ {Sin, Cos}
永言不败 2024-09-02 05:25:29

Mathematica 正在尝试在替换之前评估 Plot。您可以使用 Hold 和 ReleaseHold 函数来防止这种情况:

ReleaseHold[Hold[Plot[f[t],{t,0,2*Pi}]] /. {{f -> Sin},{f -> Cos}}]

Hold[] 将强制整个 Plot 子表达式在执行替换时保持未简化状态,然后 ReleaseHold[] 将让它继续实际绘图。

Mathematica is trying to evaluate Plot before the substitution. You can prevent that with the Hold and ReleaseHold functions:

ReleaseHold[Hold[Plot[f[t],{t,0,2*Pi}]] /. {{f -> Sin},{f -> Cos}}]

Hold[] will force the entire Plot subexpression to remain unsimplified while the substitution is performed, then ReleaseHold[] will let it proceed with the actual plotting.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文