3

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?

Margus
  • 19,694
  • 14
  • 55
  • 103
  • Margus, if you have more *Mathematica* related questions I recommend you join us on http://mathematica.stackexchange.com -- it is far more active now than StackOverflow (for mathematica tag) and you will get better answers sooner. – Mr.Wizard Feb 05 '12 at 00:20
  • Margus: PE level 12. Well done! – Mr.Wizard Feb 05 '12 at 00:33

2 Answers2

4

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.

Mr.Wizard
  • 24,179
  • 5
  • 44
  • 125
  • interesting use of `Unevaluated`. I thought you would have to do a `Hold` and `ReleaseHold` to get that to work. ...but of course that doesn't :) ...sometimes you just need to see it running to know what to do – Mike Honeychurch Feb 05 '12 at 00:20
  • @Mike admittedly `Unevaluated` is rather unpredictable. See Leonid's comments to [this answer.](http://stackoverflow.com/a/5723277/618728) – Mr.Wizard Feb 05 '12 at 00:22
  • I must admit I would have expected the expression to remain unevaluated. I don;t work with held and unevaluated expressions that much and because of that generally don;t have an intuitive feel for it. `With` with `HoldForm` is about as sophisticated as I get :) – Mike Honeychurch Feb 05 '12 at 00:24
  • @Mike notice that `Unevaluated` only extends to the LHS of `/.` and in fact that part *doesn't* evaluate; ReplaceAll sees the unevaluated form and does the replacement, but Unevaluated does not persist outside of the surrounding function (in this case ReplaceAll) and therefore evaluation continues. – Mr.Wizard Feb 05 '12 at 00:27
3

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] 
Mike Honeychurch
  • 1,683
  • 10
  • 17