为什么表达式替换不起作用?(Why does this expression substitution not work?)

我想用wolframalpha找出一条线y = ax + b通过point [2,8]的概率,当a和b由公平的掷骰子决定时。

这就是我想要的:

Count[Flatten[Table[a 2 + b, {a,6},{b,6}]],8]/ Length[Flatten[Table[a 2 + b, {a,6},{b,6}]]]

,但我不喜欢重复。 我不完全确定为什么以下不会工作:

Count[x, 8]/Length[x] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

我能解决这个问题吗?发生了什么?

I want to use wolframalpha to find the probability of a line y = a x + b passes through the point [2,8], when a and b are determined by fair dice roll.

This does what i want:

Count[Flatten[Table[a 2 + b, {a,6},{b,6}]],8]/ Length[Flatten[Table[a 2 + b, {a,6},{b,6}]]]

, but I don't like the repetition. I'm not fully certain why following will not work:

Count[x, 8]/Length[x] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

Can i get around this and what is happening?

最满意答案

评估顺序不是你想要的:

Count[x, 8]/Length[x] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

/.的左侧/. 在替换前评估,因此变为: Indeterminate

你需要推迟评估。 正常的方法是使用“纯函数”。 请参阅功能&和插槽# :

Count[#, 8]/Length[#] & @ Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

可以强制ReplaceAll(简写形式)工作,但它是非标准的:

Unevaluated[ Count[x, 8]/Length[x] ] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

这里的评估Unevaluted让左侧过早评估。

The order of evaluation in this is not what you desire:

Count[x, 8]/Length[x] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

The left side of /. evaluates before replacement, and therefore becomes: Indeterminate

You need to delay evaluation. The normal method for this is to use a "pure function." See Function & and Slot #:

Count[#, 8]/Length[#] & @ Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

It is possible to force ReplaceAll (short form /.) to work, but it is nonstandard:

Unevaluated[ Count[x, 8]/Length[x] ] /. x -> Flatten[Table[a 2 + b, {a, 6}, {b, 6}]]

Unevaluted here keeps the left-hand side from evaluating prematurely.

更多推荐