Reputation: 20058
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?
Upvotes: 4
Views: 336
Reputation: 1683
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]
Upvotes: 3
Reputation: 24336
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.
Upvotes: 5