6
$\begingroup$

I would like to generate random convex quadrilaterals using circles, my tutor has suggested to using randomreal to generate 4 numbers and scale the sum of them to 2pi, and then use trigonometry properties to do that, I do not see how that works, can somebody gives some hints about how I should go with it then I can try it out.

$\endgroup$
  • 3
    $\begingroup$ "Use trigonometry" means place them on the unit circle. Then connect the dots. $\endgroup$ – Daniel Lichtblau Dec 16 '18 at 15:18
6
$\begingroup$

Maybe this way?

n = 1000;
x = RandomReal[{0, 2 Pi}, {n, 5}];
x[[All, 2 ;;]] *= Divide[(2. Pi), (x.{0., 1., 1., 1., 1.})];
x = x.UpperTriangularize[ConstantArray[1., {5, 4}]];
quads = Transpose[{Cos[x], Sin[x]}, {3, 1, 2}];

Convexity test:

And @@ (Graphics`PolygonUtils`PolygonConvexQ /@ quads)

True

$\endgroup$
  • $\begingroup$ maybe we only use random four points on the circle and to construct a quadrilateral? $\endgroup$ – Chonglin Zhu Dec 16 '18 at 15:48
  • $\begingroup$ Certainly, this is a trivial problem in the sense that it can be tackled in many ways. I just tried to make it fast by using as much vectorized operations and matrix arithmetic as possible. On my machine, the code above generates about 3 million quadrilaterals per second. $\endgroup$ – Henrik Schumacher Dec 16 '18 at 15:59
  • $\begingroup$ Thanks, this is very helpful! $\endgroup$ – Chonglin Zhu Dec 16 '18 at 16:00
  • $\begingroup$ You're welcome! $\endgroup$ – Henrik Schumacher Dec 16 '18 at 16:00
3
$\begingroup$
ClearAll[randomQuad]
randomQuad = SortBy[#, ArcTan @@ # &] & /@ RandomPoint[Circle[], {#, 4}] &;

SeedRandom[777]
Graphics[{Circle[], 
  {Opacity[.5], EdgeForm[Gray], RandomColor[], Polygon@#} & /@ randomQuad[5]}]

enter image description here

$\endgroup$
3
$\begingroup$

Here's a fun way to use Henrik's stuff (and some other nicely vectorized operations):

n = 550;
x = RandomReal[{0, 2 Pi}, {n, 5}];
x[[All, 2 ;;]] *= Divide[(2. Pi), (x.{0., 1., 1., 1., 1.})];
x = x.UpperTriangularize[ConstantArray[1., {5, 4}]];
quads = Transpose[{Cos[x], Sin[x]}, {3, 1, 2}];
disks = {Range[2, 3], Range[7, 8] , Range[12, 15]};
shiftQuads = quads +
   RandomChoice[Flatten@disks, n]*
    Transpose[
     ConstantArray[{Cos[Subdivide[0., 2. \[Pi], n - 1]], 
       Sin[Subdivide[0., 2. \[Pi], n - 1]]}, 4], {2, 3, 1}];

{
  Opacity[.15],
  Annulus[{0, 0}, {-1, 1} + MinMax@#] & /@ disks,
  Thread@{Opacity[.5], RandomColor[n], Thread[Polygon@shiftQuads]}
  } // Graphics

enter image description here

$\endgroup$
  • $\begingroup$ Great! I will have a try, so many thanks! $\endgroup$ – Chonglin Zhu Dec 18 '18 at 2:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.