Optimizing a “Manipulate” in Mathematica

与世无争的帅哥 提交于 2019-12-06 03:58:16

The primary reason for the slowness is because you're calculating the EuclideanDistance of all the points till step i for every step i. You'll see a difference if you take this step out of the Manipulate.

prob = MapIndexed[#1/#2 &, Accumulate[
    EuclideanDistance[{0, 0}, #] < 1 & /@ arrows // Boole]] ~ N ~ 4;

Heike's solution is much smoother than yours or Nasser's so I'll use that as an example. You'd use the pre-calculated value of prob in it as:

Manipulate[
 Graphics[{White, Rectangle[{-5, -5}, {5, 5}], Red, Disk[{0, 0}, 1], 
   Black, Point[arrows[[;; i]]], 
   Text[Style[First@prob[[i]], Bold, 18, "Helvetica"], {-4.5, 4.5}]}, 
  ImageSize -> 200], {i, Range[2, 20000, 1]}, 
 ControlType -> Manipulator, SaveDefinitions -> True]

I've set the precision uniformly to 4 digits, because otherwise, you'll see the figure jump around when the number of significant digits changes.

Maybe something like this

Manipulate[
 Graphics[{White, Rectangle[{-5, -5}, {5, 5}],
   Red, Disk[{0, 0}, 1],
   Black, Point[arrows[[;; i]]], 
   Text[Style[Count[arrows[[;; i]], a_ /; (Norm[a] < 1)]/i // N, Bold,
      18, "Helvetica"], {-4.5, 4.5}]}, ImageSize -> 800], {i, 
  Range[2, 20000, 1]}, ControlType -> Manipulator, 
 SaveDefinitions -> True]

See if this is any better for you:

Manipulate[

 Graphics[{
   White,
   Rectangle[{-5, -5}, {5, 5}],
   Red,
   Disk[{0, 0}, 1],
   Black, Point /@ (arrows[[;; i]]), 
   Text[Style[
     Dynamic@Total[
         If[# < 1, 1, 0] & /@ (EuclideanDistance[{0, 0}, #] & /@ 
            arrows[[;; i]])]/Length@arrows[[;; i]] // N, Bold, 18, 
     "Helvetica"], {-4.5, 4.5}]}, ImageSize -> 200],

 {{i, 2, "i"}, 2, 20000, 1, Appearance -> "Labeled"},
 TrackedSymbols :> {i},
 SynchronousUpdating -> False,
 AppearanceElements -> All,


 Initialization :>
  (
   arrows = 
     ParallelTable[{RandomVariate[NormalDistribution[0, Sqrt[1]]], 
       RandomVariate[NormalDistribution[0, Sqrt[1]]]}, {20000}];
   )

 ]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!