The function is given by
fun[x_, z_] := a (1 - z^2) Cos[x]^2 - (b z^2 + z - c)
We define a function that generates a random point in the x
-z
plane that satisfies fun[x, z] > 0
:
accept[a0_, b0_, c0_] :=
Block[{a = a0, b = b0, c = c0, x = RandomReal[{0, 6}], z = RandomReal[{-1, 1}]}
, If[fun[x, z] > 0, {x, z}, accept[a, b, c]]
]
Important note: this definition is dangerous, because it is recursive. You should make sure that there are actually a good number of x
-z
pairs that satisfy fun[x, z] > 0
first before using this definition, because it runs the risk of running into the $RecursionLimit
. As it is, it randomly generates a point, and if it satisfies the condition, it keeps it, and if it doesn't, then the function calls itself. Thus, it will eventually spit out a point if there is one to be found (or rather, if acceptable region is not too small).
Alternatively, you can define this function with a so-called "vanishing function" (named Nothing
in Mathematica 10.1 and later) as
acceptReject[a0_, b0_, c0_] :=
Block[{a = a0, b = b0, c = c0, x = RandomReal[{0, 6}], z = RandomReal[{-1, 1}]}
, If[fun[x, z] > 0, {x, z}, ##&[]]
]
This will return literally nothing if the point doesn't satisfy the condition, and so when you make a Table
of points, you will get only a list of points that satisfy the condition. However, the list of points won't necessarily be as many points as you specify, because it doesn't try to find another point if the random point that it chose doesn't fit the criterion; rather, it just moves on.
That said, we can generate a table of points via
points = Table[accept[3, -2, -2], {500}];
and we can plot the function along with these points to make sure that we are generating a uniform sample from the region:
Show[
Plot3D[Evaluate[fun[x, z] /. {a -> 3, b -> -2, c -> -2}]
, {x, 0, 6}, {z, -1, 1}
, RegionFunction -> Function[#3 > 0]
, Mesh -> None
, PlotStyle -> Opacity[0.3]
]
, Graphics3D[Point[{##, 0} & @@@ points]]
]

fun[x,z] >0
. If so, keep it. If not, throw it out. This is called rejection sampling (or the accept-reject Monte Carlo algorithm). $\endgroup$