Why does this expression substitution not work?

319 views Asked by At

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?

2

There are 2 answers

4
Mr.Wizard On BEST ANSWER

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.

2
Mike Honeychurch On

The reason this produces an error is because x has no value and Length[x] returns zero. What you need to do is define x:

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