<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel rdf:about="https://community.wolfram.com">
    <title>Community RSS Feed</title>
    <link>https://community.wolfram.com</link>
    <description>RSS Feed for Wolfram Community showing any discussions tagged with Tuning and Debugging sorted by most viewed.</description>
    <items>
      <rdf:Seq>
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/2330900" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/181641" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1763688" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/293403" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/148526" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/162697" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/133035" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/290818" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1108896" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1037730" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/286203" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1855244" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1857499" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/1931315" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/175914" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/93435" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/159073" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/190372" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/227021" />
        <rdf:li rdf:resource="https://community.wolfram.com/groups/-/m/t/138207" />
      </rdf:Seq>
    </items>
  </channel>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/2330900">
    <title>[WSG21] Daily Study Group: programming tutorials</title>
    <link>https://community.wolfram.com/groups/-/m/t/2330900</link>
    <description>Daily Study Groups are back, now providing expertise on practical programming! After a short break, we&amp;#039;re starting up with a series that picks up where Wolfram Language Basics sessions ended. This 3-week series will take you from basic programming concepts to package development. &#xD;
&#xD;
Need tips on improving your code’s speed or functionality? Programming Tutorials offer a great opportunity to level-up your skills while interacting with software development professionals. See hands-on examples and get questions answered by Wolfram Language experts. Plus: participants who pass weekly quizzes are awarded a program completion certificate. Level 1 certification is available for those who pass manually graded exercises. &#xD;
&#xD;
Join us any time between August 2 and August 20! Check out our [registration page][1] for more details.&#xD;
&#xD;
&#xD;
&#xD;
 [1]: https://wolfr.am/Study_Group15</description>
    <dc:creator>Wolfram U</dc:creator>
    <dc:date>2021-07-30T15:24:02Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/181641">
    <title>An experiment in Moment of Inertia with Raspberry Pi / Arduino</title>
    <link>https://community.wolfram.com/groups/-/m/t/181641</link>
    <description>Wanted to share with my kids the classical experiment on a rolling object down an incline plane using legos, arduino and Mathematica for the Raspberry Pi.

Using a window valance and some lego technic pieces we proceeded to build the inclined plane platform.

[img=width: 300px; height: 400px;]/c/portal/getImageAttachment?filename=inclinedplane1.JPG&amp;amp;userId=78214[/img]

Using legos was great to allow to attach both leds and photorresistors to the inclined plane. It also allowed us to set up build a platform from where to attach a servo motor and a protractor to measure the angle of inclination.
[img=width: 400px; height: 533px;]/c/portal/getImageAttachment?filename=inclinedplane2.JPG&amp;amp;userId=78214[/img]

We&amp;#039;ll detect when the ball reaches a certain point of the platform by the the disminution of the LED light received at the photoresistors.
[img=width: 300px; height: 400px;]/c/portal/getImageAttachment?filename=8270photo(1).JPG&amp;amp;userId=78214[/img]

The adafruit web site is a very good site to explain the details on how to connect the photoresistors and leds to the Arduino.
[url=http://learn.adafruit.com/adafruit-arduino-lesson-2-leds/leds]http://learn.adafruit.com/adafruit-arduino-lesson-2-leds/leds[/url]
[url=http://learn.adafruit.com/photocells/using-a-photocell]http://learn.adafruit.com/photocells/using-a-photocell[/url]

As the readings of the photocells require of analog inputs, we decided to use a spare arduino we had at our disposal, and to have more fun, use XBEE modules to connect the arduino to the raspberry pi.
[img=width: 300px; height: 225px;]/c/portal/getImageAttachment?filename=6471photo(2).JPG&amp;amp;userId=78214[/img]

The following is the code at the Arduino.[code]
#include &amp;lt;Servo.h&amp;gt; 
int servoPin = 9;
int LightSensor[4]={A1,A2,A3,A4};
int current[4]={0,0,0,0};
double timers[4]={0,0,0,0};
int previous[4]={0,0,0,0};

Servo servo;  
int i=0; 
double factor=0.7;
double timer = 0; 
int inByte =0;

void setup() 
{ 
  Serial.begin(19200);
  servo.attach(servoPin); 
  servo.write(0);
  delay(2000);
  for (i=0;i&amp;lt;4;i++){
    previous[i]=analogRead(LightSensor[i]);
  }
} 
void loop() 
{ 
if(Serial.available()&amp;gt;0){

  inByte=Serial.read();

 if (inByte==65) {
    servo.write(90);
    timer=millis();
    trackBall();
    for (i=0;i&amp;lt;4;i++){
      Serial.println(timers[i]);
    }
    servo.write(0);
  }
}
}

void trackBall(){
 int m =0;
  while (m&amp;lt;4){
    current[m]=analogRead(LightSensor[m]);
    if (current[m]&amp;lt;factor*previous[m]){
      timers[m]=millis()-timer;
      m++;
  }
  }
}[/code]
Mathematica code and results to follow
[mcode]serial = DeviceOpen[&amp;#034;Serial&amp;#034;, {&amp;#034;/dev/ttyUSB0&amp;#034;, &amp;#034;BaudRate&amp;#034; -&amp;gt; 19200}]
lengths = {0., 0.175, 0.43, 

   0.69} ;(*Distance between light sensors in meters*)
data = {};(*List to capture the time between sensors*)
ping := Module[{}, DeviceWriteBuffer[serial, {&amp;#034;A&amp;#034;}]; Pause[3]; 

  ToExpression[StringSplit[FromCharacterCode[DeviceReadBuffer[serial]]]]/1000]
(*Function pings sends an &amp;#034;A&amp;#034; to the arduino to release the ball and \

collect timing*)
Button[&amp;#034;Collect Data&amp;#034;, data = Append[data, ping]]
Dynamic[tdata = Transpose@data;

 dataPoints = 

  Flatten[Table[{tdata[[i, j]], lengths[[i]]}, {i, 

     Length[lengths]}, {j, Length[data]}], 1];

 lm = Fit[dataPoints, {1, x, x^2}, x];

 Plot[lm, {x, -0.3, 1.2}, 

  Epilog -&amp;gt; {Red, PointSize[Large], Point[dataPoints]}, 

  AspectRatio -&amp;gt; 1, PlotLabel -&amp;gt; lm]][/mcode]Using a hollow ball, we can work out the gravity value
[img=width: 440px; height: 500px;]/c/portal/getImageAttachment?filename=Untitled.png&amp;amp;userId=78214[/img]

Using a golf ball
[img=width: 500px; height: 482px;]/c/portal/getImageAttachment?filename=InclinedPlane.png&amp;amp;userId=78214[/img]

A couple of videos of the experiment in action
[url=https://www.youtube.com/watch?v=4eRZ48N3vM8]https://www.youtube.com/watch?v=4eRZ48N3vM8[/url]
[url=https://www.youtube.com/watch?v=eLVPpEcyw_0]https://www.youtube.com/watch?v=eLVPpEcyw_0[/url]
[url=https://www.youtube.com/watch?v=53WaEcRWY_0]https://www.youtube.com/watch?v=53WaEcRWY_0[/url]</description>
    <dc:creator>Diego Zviovich</dc:creator>
    <dc:date>2014-01-08T01:09:54Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1763688">
    <title>[LiVE] Request for suggestions for a livestreamed &amp;#034;Bugs Review&amp;#034; event</title>
    <link>https://community.wolfram.com/groups/-/m/t/1763688</link>
    <description>**Update: This event is scheduled for 9/6/2019 at 3:30pm US Central timezone.**&#xD;
&#xD;
We are planning to have our live-streamed &amp;#034;Bugs Review&amp;#034; event soon, where Stephen Wolfram will discuss issues (bugs: incorrect behaviors, crashes, hangs, performance issues, etc.) that you care the most about. If you plan to attend and to help prepare for this event, please reply to this post with issues in the Wolfram Language (including the Notebook Interface) you think are the most important to discuss.&#xD;
&#xD;
Thanks!</description>
    <dc:creator>Arnoud Buzing</dc:creator>
    <dc:date>2019-08-14T17:04:55Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/293403">
    <title>Issues with AstronomicalData and SunPosition</title>
    <link>https://community.wolfram.com/groups/-/m/t/293403</link>
    <description>TL;DR
---
I have three issues with getting sun positions in Mathematica V10:

 - It is extremely slow compared to V9
 - It doesn&amp;#039;t *seem* to yield correct results
 - a) It needs an Internet connection, which b) is not assured to always return results and c) if not used optimally can easily consume your monthly allowance of W|A calls

Long story
===
With the advent of V10 `AstronomicalData` has been deprecated, as shown on its documentation page:
![enter image description here][1].

I&amp;#039;m not an astronomer, so my main use of this function has been restricted to its capability to get the sun position using functions calls like this:

    {
      AstronomicalData[&amp;#034;Sun&amp;#034;, {&amp;#034;Azimuth&amp;#034;, {2013, 3, 1, #, 0, 0}, {52.37`, 4.89`}}, TimeZone -&amp;gt; 1], 
      AstronomicalData[&amp;#034;Sun&amp;#034;, {&amp;#034;Altitude&amp;#034;, {2013, 3, 1, #, 0, 0}, {52.37`, 4.89`}},  TimeZone -&amp;gt; 1]
    } &amp;amp; /@ Range[0, 23]

&amp;gt; {{341.47732, -43.93930}, {2.33417, -45.21747}, {22.94232, -43.19133},
&amp;gt; {41.52167, -38.28400}, {57.55208, -31.30276}, {71.47253, -23.03159},
&amp;gt; {84.02194, -14.08294}, {95.91940, -4.92723}, {107.80166, 4.03418}, {120.23770, 12.40167}, {133.72303, 19.72563}, {148.59433, 
&amp;gt;   25.48377}, {164.84179, 29.12209}, {181.93103, 30.19428}, {198.91284,
&amp;gt;    28.55117}, {214.89602, 24.41962}, {229.46400, 
&amp;gt;   18.28613}, {242.70064, 10.70703}, {254.98998, 
&amp;gt;   2.19073}, {266.84760, -6.82566}, {278.85594, -15.94505},  {291.66723, -24.75464}, {306.00911, -32.75641}, {322.57956, 
&amp;gt; -39.29877}}

So, this gets me the sun positions in steps of an hour during a particular day in Amsterdam (TZ 1).

The same call still works in V10, though it now returns numbers with units; degrees in this case. On its first call, it reads some paclet information from a Wolfram server, but on any successive call no Internet connection is needed. I will be going into detail about timing further on, but I&amp;#039;ll say here that the V10 function takes about three times longer than its V9 namesake. I blame the addition of units for that.

With `AstronomicalData` apparently deprecated we are supposed to use its successors. In this case I need `SunPosition`. A direct translation of the above would be:

    SunPosition[GeoPosition[{52.37`, 4.89`}], DateObject[{2013, 3, 1, #, 0, 0}, TimeZone -&amp;gt; 1]] &amp;amp; /@ Range[0, 23]

&amp;gt; {{95.7, -5.1}, {107.6, 3.9}, {120.0, 12.3}, {133.5, 19.6}, {148.3, 25.4}, {164.5, 29.1}, {181.6, 30.2}, {198.6, 28.6}, {214.6, 24.5}, {229.2, 18.4}, {242.5, 10.9}, {254.8, 2.4}, {266.6, -6.7}, {278.6, -15.8}, {291.4, -24.6}, {305.7, 
-32.6}, {322.2, -39.2}, {341.3, -43.5}, {2.0, -44.8}, {22.5, -42.9}, 
{41.1, -38.0}, {57.1, -31.1}, {71.0, -22.9}, {83.6, -13.9}}

As with the new `AstronomicalData` the output is actually in degrees which I have removed in the above output for the sake of clarity. There are a few things to note:

 - `SunPosition` uses position and date objects, the latter being new in V10
 - `SunPosition` does not have a `TimeZone` option, but you can set it in `DateObject`
 - `SunPosition` can use the old lat/long list position indication. It also can use a date list to enter the date instead of a `DateObject`. In the latter case you are out of options with respect to time zones and you have to add the appropriate amount of time offset
 - It is extremely slow, and it may even time-out: 

![enter image description here][2]

 - Last but not least: the results seem to be plain wrong. It suggests that sunrise is somewhat before 1 am, which is -of course- incorrect. I assume that this has something to do with a `$GeoLocation` setting for the observer of the sun positions, but I haven&amp;#039;t managed to sort out what I am supposed to enter to get the correct sun positions for the location provided in the same call.

As to timing: I noticed very inconsistent timings for `SunPosition` compared to `AstronomicalData`, so I used the following code to collect a somewhat more statistical  sound sample:

    SetAttributes[timingTest, HoldFirst];
    timingTest[code_, repeats_Integer] :=
       Table[
          ClearSystemCache[];
          code // AbsoluteTiming // First,
          {repeats}
        ]

Using this, I collected timing of 20 calls to the following code snippets:

 - `AstronomicalData` V9 and V10: As above
 - `SunPosition`: As above
 - `SunPosition` without `GeoPosition`, just the lat/long list.
 - `SunPosition`  without `GeoPosition`, and also without the `DateObject` date, just a classical date list (with the hour set to +1 to accommodate TZ 1)
 - `SunPosition` V10 without `GeoPosition` and with the `Map` (`/@`) gone and replaced by a `DateRange` inside the call.

In the last case, the returned value is a `TimeSeries` object from which I extract the positions using the `&amp;#034;Paths&amp;#034;` method:

     SunPosition[{52.37`, 4.89`}, DateRange[{2013, 3, 1, 1, 0, 0}, {2013, 3, 1, 24, 0, 0}, &amp;#034;Hour&amp;#034;]][&amp;#034;Paths&amp;#034;][[1, All, 2]]

The results were as follows:

![enter image description here][3]

Clearly, the `SunPosition` results are very disappointing. Getting the sun positions with `SunPosition` is almost 40 times slower than using the old V9 method (which, I should add, wasn&amp;#039;t particularly quick either. I have an implementation in Mathematica code which is faster). The V10 implementation of `AstronomicalData` is also more than three times slower than the V9 version. The `DateRange` version of the call saves a lot of communication overhead. Still, it is almost *five times slower* than in V9.

The cause of all this slowness is that `SunPosition` simply does a call to Wolfram|Alpha. Sniffing the communication one sees the following string passed to the server:

    &amp;#034;1:eJxTTMoPSuNgYGAoZgESPpnFJcHcQEZwaV5AfnFmSWZ+XhoTsmxR/6GvGjH9wg4Qhr6XQxobsnzmXXYGhkxmIC+TEUSIgwggZihigIJgoAIGj/yizKr8PJigA5yBZtubwB1yrdxeDkXVIuvcH1aJOBRzAqUcS0vycxNLMpMBSAArww==&amp;#034;

which can be turned into readable form using `Uncompress`:

    {&amp;#034;SunPosition&amp;#034;, {4.89, 52.37}, {2013, 3, 1, 23, 0, 0.}, &amp;#034;Horizon&amp;#034;, 2., 2., {52.09, 5.12}, Automatic}

Here, we can recognize the lat/long of the position I used (but with lat/long reversed - Is this somehow significant?). At the end is my own `$GeoLocation`, but I don&amp;#039;t believe it is used at all (and it shouldn&amp;#039;t: I&amp;#039;m asking for the sun position over Amsterdam, not where I live). Changing it with `Block` I get the same results:

    Block[{$GeoLocation = GeoPosition[{52.37`, 40.89`}]}, SunPosition[{52.37`, 4.89`}, {2013, 3, 1, 1, 0, 0}]]

Apart from the slowness, there&amp;#039;s the issue of the necessary Internet connectivity (Want to give a demonstration and you don&amp;#039;t have Internet? Sorry, you&amp;#039;re out of luck). 

And what of the use of W|A calls? Each of the `SunPosition` tests (except the last one) took me 20 * 24 = 480 calls. So this part of my testing only already took 1440 calls, and one should be reminded that a typical Home Use license allows for only 3,000 calls per month. Things like this can go pretty fast. In fact, I once wrote an application that calculates the impact of building changes on shadows around your house throughout the year. It does in the order of 17,000 `AstronomicalData` calls. I couldn&amp;#039;t implement that naively using `SunPosition` and have it actually work. Clearly, one should now use the `DateRange` version of the call as much as possible.

----------

To wrap up: I have one real question, i.e., how to get `SunPosition` to return the same values as `AstronomicalData`, and a request to the WRI team: please put `SunPosition` in the kernel and don&amp;#039;t use W|A calls, because the situation as it is now is rather annoying and IMHO a real step backwards.

  [1]: /c/portal/getImageAttachment?filename=AstronomicalData.png&amp;amp;userId=43903
  [2]: /c/portal/getImageAttachment?filename=timeout.png&amp;amp;userId=43903
  [3]: /c/portal/getImageAttachment?filename=results.png&amp;amp;userId=43903</description>
    <dc:creator>Sjoerd de Vries</dc:creator>
    <dc:date>2014-07-13T16:39:48Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/148526">
    <title>Chromatic polynomials for custom graphs</title>
    <link>https://community.wolfram.com/groups/-/m/t/148526</link>
    <description>1 ) How to use the math functions over graphs  that are not in the data graph of Mathematica?
2 ) How to compute Chromatic Poynomials for a graph introduced by myself ?</description>
    <dc:creator>Reinaldo Giudici</dc:creator>
    <dc:date>2013-11-04T13:57:36Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/162697">
    <title>Problem using WhenEvent to constrain solution</title>
    <link>https://community.wolfram.com/groups/-/m/t/162697</link>
    <description>[b]Note: This question has also been posted at [url=http://mathematica.stackexchange.com/questions/37907/problem-using-whenevent-to-constrain-solution]http://mathematica.stackexchange.com/questions/37907/problem-using-whenevent-to-constrain-solution[/url][/b]

Hi guys.

Problem: Simulate pressure in volumes for 1 second. 

The circuit is as follows:

[img=float: left; width: 343px; height: 174px;]/c/portal/getImageAttachment?filename=6209Circuit.jpg&amp;amp;userId=99808[/img]










From this I set up the governing DE for both volumes and plot the solution:
[mcode]Ad1 = 10/1000^2;

Ad2 = 1.5*1000^(-2);

Ad3 = 1.5*1000^(-2);

Cd1 = 0.67;

Cd2 = 0.67;

Cd3 = 0.67;

V1 = 10/1000;

V2 = 10/1000;

Rho = 875;

beta = 1000*10^6;

ps = 100*10^5;

Q1 = Ad1*Cd1*Sqrt[(2/Rho)*(ps - p1[t])];

Q2 = Ad2*Cd2*Sqrt[(2/Rho)*(ps - p2[t])];

Q5 = Ad3*Cd3*Sqrt[(2/Rho)*(p1[t] - p2[t])];

Q3 = Q1 - Q5;

Q4 = Q2 + Q5;

s = NDSolve[{p1&amp;#039;[t] == (beta*Q3)/V1, p2&amp;#039;[t] == (beta*Q4)/V2, 

    p1[0] == p2[0] == 0, WhenEvent[p1[t] &amp;gt;= ps, p1[t] -&amp;gt; ps], 

    WhenEvent[p2[t] &amp;gt;= ps, p2[t] -&amp;gt; ps]}, {p1, p2}, {t, 0, 1}];

Plot[Evaluate[{p1[t]/10^5, p2[t]/10^5} /. s], {t, 0, 1}][/mcode]Output:

[img=float: left; width: 800px; height: 490px;]/c/portal/getImageAttachment?filename=Problem1.jpg&amp;amp;userId=99808[/img]


























Mathematica aborts integration after t=0.69 since it encounters complex solutions. This is due to p1 and p2 at some point getting larger than ps, which makes no sense, particularly since I have added 2 &amp;#039;WhenEvent&amp;#039;s which shouldn&amp;#039;t &amp;#039;allow&amp;#039; p1 and p2 to be greater than ps (see code). Complex solutions can be avoided by adding &amp;#039;Abs&amp;#039;, however, then the solution seem to completely diverge:

[img=float: left; width: 800px; height: 490px;]/c/portal/getImageAttachment?filename=Problem1_2.jpg&amp;amp;userId=99808[/img]























[b]
[/b][b]
Question: Why doesn&amp;#039;t the &amp;#039;WhenEvent&amp;#039;s seem to &amp;#039;work&amp;#039;?

[/b]PS.; I have obtained a more credible solution using[b] Matlab [/b]and the same constrictions:

[img=float: left; width: 800px; height: 470px;]/c/portal/getImageAttachment?filename=Problem1_3.jpg&amp;amp;userId=99808[/img]

























[b]

Matlab code:

[/b][mcode]close all;
[b][/b]
clear;

%Basic data

EndTime=1;

StepTime=1e-5;

ps=100*1e5;

Cd1=0.67;

Cd2=0.67;

Cd3=0.67;

Ad1=10*1000^(-2);

Ad2=1.5*1000^(-2);

Ad3=1.5*1000^(-2);

V1=10/1000;

V2=10/1000;

rho=875;

beta=1000*1e6;



%Initialize

p1_initial=0;

p2_initial=0;

%Initially old values are simply set to current values

Time=0.0;

p1=p1_initial;

p2=p2_initial;





%Initialize counters so that plot data is only saved once pr. a number of

%time steps corresponding to ReportInterval

ReportCounter=0;

ReportInterval=10;

Counter=ReportInterval;

%Start time integration

while Time&amp;lt;EndTime

if p1&amp;gt;=ps

    p1=ps;

end

if p2&amp;gt;=ps

    p2=ps;

end

        Q1=Cd1*Ad1*sqrt(2/rho*(ps-p1));

        Q2=Cd2*Ad2*sqrt(2/rho*(ps-p2));

        Q5=Cd3*Ad3*sqrt(2/rho*(p1-p2));%Flow through orifice 3

        Q3=Q1-Q5;%Q3 to volume 1

        Q4=Q2+Q5;%Q4 to volume 2

        p1Dot=beta*Q3/V1;

        p2Dot=beta*Q4/V2;

        

        

        %report

        if Counter==ReportInterval

            Counter=0;

            ReportCounter=ReportCounter+1;

            Time_Plot(ReportCounter)=Time;

            p1_Plot(ReportCounter)=p1*1e-5;

            p2_Plot(ReportCounter)=p2*1e-5;

            

            

        end;

        %Time integrate

        p1=p1+p1Dot*StepTime;

        p2=p2+p2Dot*StepTime;

        Time=Time+StepTime;

        Counter=Counter+1;

    end;

    plot(Time_Plot,p1_Plot);

    hold on;

    plot(Time_Plot,p2_Plot,&amp;#039;r&amp;#039;);

    grid;[/mcode]Matlab solution seems to be a good fit to simulated results (from SimulationX):

[img=float: left; width: 800px; height: 396px;]/c/portal/getImageAttachment?filename=simulation.jpg&amp;amp;userId=99808[/img]</description>
    <dc:creator>Julian Lovlie</dc:creator>
    <dc:date>2013-11-30T18:38:36Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/133035">
    <title>Is there a way to have Mathematica ignore images when saving notebooks?</title>
    <link>https://community.wolfram.com/groups/-/m/t/133035</link>
    <description>Hello,

I&amp;#039;m currently working on an image processing project and I typically have several high resolution images in output cells of my notebook as I test different filters, etc. The problem is that this causes the notebook file to become very large, and saving causes the system to temporarily freeze while it is &amp;#034;Checking&amp;#034; the notebook prior to saving. With just 5 or 6 images in my notebook, saving can take 15-20 seconds, during which time I cannot do anything else in Mathematica.

As someone who compusively needs to save documents every few seconds, this becomes a huge inconvenience. Since I don&amp;#039;t need to save the images themselves (the originals are on disk already), I usually delete any visible images in the notebook before saving to make sure it will complete in a reasonable amount of time, but while I&amp;#039;m working I often need to keep some images handy so I can compare results. Does anyone know of a preference or setting somewhere that can make Mathematica save notebooks without visible images?</description>
    <dc:creator>Richard Hennigan</dc:creator>
    <dc:date>2013-10-01T07:41:22Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/290818">
    <title>Mathematica V10 execution time has grown up to 12% to 45% from V9</title>
    <link>https://community.wolfram.com/groups/-/m/t/290818</link>
    <description>A simple example: RosettaCode&amp;#039;s [Universal Turing Machine][1]
(5-state, 2-symbol probable Busy Beaver machine from Wikipedia)
In V9 time = 225 seconds, in V10 322 seconds   (Windows i5 desktop).
 
Not much to do but hope for better performance.  I think I hear more disk swapping but that&amp;#039;s not measured (yet).


  [1]:http://rosettacode.org/wiki/Universal_Turing_machine#Mathematica</description>
    <dc:creator>Douglas Kubler</dc:creator>
    <dc:date>2014-07-10T20:23:05Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1108896">
    <title>Improvement on the magic number 0x5f3759df</title>
    <link>https://community.wolfram.com/groups/-/m/t/1108896</link>
    <description>One of the well-known algorithm of doing the inverse square root:&#xD;
&#xD;
$$\frac{1}{\sqrt{x}}$$&#xD;
&#xD;
is the so-called &amp;#034;fast inverse square root&amp;#034; algorithm, see [wikipedia][1]. This code gives a very good approximation of this function, possibly good enough for lighting in video-games. Even now, with modern CPUs, with many new instructions, this is still quite a bit faster than the actual inverse square root. The most surprising thing about this code is the appearance of a magic constant (note that this is C code, including the original comments)&#xD;
&#xD;
    float Q_rsqrt( float number )&#xD;
    {&#xD;
    	long i;&#xD;
    	float x2, y;&#xD;
    	const float threehalfs = 1.5F;&#xD;
    &#xD;
    	x2 = number * 0.5F;&#xD;
    	y  = number;&#xD;
    	i  = * ( long * ) &amp;amp;y;                       // evil floating point bit level hacking&#xD;
    	i  = 0x5f3759df - ( i &amp;gt;&amp;gt; 1 );               // what the f*ck? &#xD;
    	y  = * ( float * ) &amp;amp;i;&#xD;
    	y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration&#xD;
&#xD;
        return y;&#xD;
    }&#xD;
&#xD;
As you can see, the input is a float (a 32 bit floating point number), which is cast in to a long integer, the bits are shifted, and the result subtracted from a magic constant, this number is then re-interpreted again as a float.&#xD;
&#xD;
To understand why this works is actually quite a long story, but realise that floats are stored as 32 bits as follows:&#xD;
&#xD;
    SEEEEEEEEMMMMMMMMMMMMMMMMMMMMMMM&#xD;
&#xD;
where S= sign, E = exponent, and M = Mantissa. So once you interpret this as a long, and start shifted bits, you can get very unpredictable behavior. The question that I&amp;#039;m after is: can this constant be improved? &#xD;
&#xD;
Let&amp;#039;s create a library function in c and link it back in to Mathematica, such that we can try different magic constants and different values x:&#xD;
&#xD;
    Needs[&amp;#034;CCompilerDriver`&amp;#034;]&#xD;
    src=&amp;#034;&#xD;
    #include \&amp;#034;WolframLibrary.h\&amp;#034;&#xD;
    DLLEXPORT mint WolframLibrary_getVersion(){&#xD;
      return WolframLibraryVersion;&#xD;
    }&#xD;
    DLLEXPORT int WolframLibrary_initialize( WolframLibraryData libData) {return 0;}&#xD;
    DLLEXPORT void WolframLibrary_uninitialize( WolframLibraryData libData) {return;}&#xD;
    DLLEXPORT int constantzero(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res){&#xD;
       MArgument_setInteger(Res, 0);&#xD;
       return LIBRARY_NO_ERROR;&#xD;
    }&#xD;
    DLLEXPORT int fastinvsqrt(WolframLibraryData libData, mint Argc, MArgument *Args, MArgument Res) {&#xD;
    	double in = MArgument_getReal(Args[0]);&#xD;
    	int magic = MArgument_getInteger(Args[1]);&#xD;
    	float x = in;&#xD;
    	float halfx = 0.5f * x;&#xD;
    	int i = *(int*)&amp;amp;x;&#xD;
    	i = magic - (i &amp;gt;&amp;gt; 1); &#xD;
    	x = *(float*)&amp;amp;i;&#xD;
    	x = x*(1.5f-(halfx*x*x));&#xD;
    	double I1; &#xD;
    	I1 = x;&#xD;
    	MArgument_setReal(Res, I1);&#xD;
    	return LIBRARY_NO_ERROR;&#xD;
    }&amp;#034;;&#xD;
    Quiet@LibraryFunctionUnload[fastinvsqrt]&#xD;
    fastinvsqrtlib=CreateLibrary[src,&amp;#034;fastinvsqrt&amp;#034;]&#xD;
    fastinvsqrt=LibraryFunctionLoad[fastinvsqrtlib, &amp;#034;fastinvsqrt&amp;#034;,{Real,Integer},Real]&#xD;
    magicconst=16^^5f3759df&#xD;
    Plot[{1/Sqrt[x],fastinvsqrt[x,magicconst]},{x,0.1,5},PlotRange-&amp;gt;{0,2}]&#xD;
    LogLogPlot[{1/Sqrt[x]-fastinvsqrt[x,magicconst],1/Sqrt[x]},{x,0.01,100000},PlotRange-&amp;gt;{All,{10^-6,10}},Frame-&amp;gt;True,PlotRangePadding-&amp;gt;None,PlotPoints-&amp;gt;1200,MaxRecursion-&amp;gt;3]&#xD;
&#xD;
![enter image description here][2]&#xD;
&#xD;
The match is indeed great! and we can see that the error (second plot, in blue) is of the order 0.1% of the result for the original magic constant!&#xD;
&#xD;
Let&amp;#039;s introduce the relative error:&#xD;
&#xD;
    ClearAll[relativeerror]&#xD;
    relativeerror[x_Real, magic_Integer] := (1/Sqrt[x] - fastinvsqrt[x, magic])/(1/Sqrt[x])&#xD;
&#xD;
and plot it:&#xD;
&#xD;
    LogLogPlot[relativeerror[x, magicconst], {x, 0.01, 100000}, &#xD;
     Frame -&amp;gt; True, PlotRangePadding -&amp;gt; None, PlotRange -&amp;gt; {10^-5, 1}, &#xD;
     PlotPoints -&amp;gt; 1200, MaxRecursion -&amp;gt; 3]&#xD;
&#xD;
![enter image description here][3]&#xD;
&#xD;
This plot is periodic because of the way floating point numbers are defined/implemented, we can zoom in on one of the parts:&#xD;
&#xD;
    LogLinearPlot[relativeerror[x, magicconst], {x, 1, 4}, Frame -&amp;gt; True, &#xD;
     PlotRangePadding -&amp;gt; None, PlotRange -&amp;gt; All, PlotPoints -&amp;gt; 1200, &#xD;
     MaxRecursion -&amp;gt; 3]&#xD;
&#xD;
![enter image description here][4]&#xD;
&#xD;
We can plot slight deviations from the magic constant to see the new relative errors:&#xD;
&#xD;
    LogLinearPlot[{relativeerror[x, magicconst], &#xD;
      relativeerror[x, magicconst - 20000], &#xD;
      relativeerror[x, magicconst + 20000]}, {x, 1, 4}, Frame -&amp;gt; True, &#xD;
     PlotRangePadding -&amp;gt; None, PlotRange -&amp;gt; All, PlotPoints -&amp;gt; 1200, &#xD;
     MaxRecursion -&amp;gt; 3, PlotLegends -&amp;gt; {&amp;#034;0&amp;#034;, &amp;#034;-20000&amp;#034;, &amp;#034;+20000&amp;#034;}]&#xD;
&#xD;
![enter image description here][5]&#xD;
&#xD;
If the constant increases, the center peaks go up, but the far-right and far-left peak go down. &#xD;
&#xD;
Let&amp;#039;s try a bunch of magic-constants, and check the maximum (relative) error we find. I do this by sampling many point and looking for the maximum error I find in those points:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data = Table[{d,  Max[Table[With[{x = 2^s}, ((1/Sqrt[x] - fastinvsqrt[x, d + magicconst])/(1/Sqrt[x]))], {s, 0, 2, 0.00001}]]}, {d, -100000, 100000, &#xD;
        1000}];&#xD;
    data // ListLogPlot&#xD;
    TakeSmallestBy[data, Last, 1]&#xD;
&#xD;
![enter image description here][6]&#xD;
&#xD;
    {{0, 0.00175225}}&#xD;
&#xD;
If there is a better constant, it sure is close to the original constant. Let&amp;#039;s zoom in a bit:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data = Table[{d,  Max[Table[With[{x = 2^s}, ((1/Sqrt[x] - fastinvsqrt[x, d + magicconst])/(1/Sqrt[x]))], {s, 0, 2, 0.00001}]]}, {d, -1000, 1000, 10}];&#xD;
    data // ListLogPlot&#xD;
    TakeSmallestBy[data, Last, 1]&#xD;
&#xD;
![enter image description here][7]&#xD;
&#xD;
    {{160, 0.00175121}}&#xD;
&#xD;
We can zoom in even further:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data=Table[{d,Max[Table[With[{x=2^s},((1/Sqrt[x]-fastinvsqrt[x,d+magicconst])/(1/Sqrt[x]))],{s,0,2,0.0000001}]]},{d,160,170,1}];&#xD;
    data//ListLogPlot&#xD;
    TakeSmallestBy[data,Last,1]&#xD;
&#xD;
![enter image description here][8]&#xD;
&#xD;
    {{166, 0.00175129}}&#xD;
&#xD;
magicconstant + 166 seems to have a slightly better worst-case performance. This corresponds to the follow new magic constant:&#xD;
&#xD;
    BaseForm[magicconst + 166, 16]&#xD;
&#xD;
or in C (in hex):&#xD;
&#xD;
    0x5f375a85&#xD;
&#xD;
We could also use the built-in FindMaximum:&#xD;
&#xD;
    ClearAll[FindMaxima]&#xD;
    FindMaxima[d_Integer]:=Module[{x},&#xD;
        Max[Table[First@FindMaximum[((1/Sqrt[x]-fastinvsqrt[x,d+magicconst])/(1/Sqrt[x])),{x,x0,1,4},MaxIterations-&amp;gt;5000,WorkingPrecision-&amp;gt;50],{x0,1.0,4.0,0.03}]]&#xD;
    ]&#xD;
&#xD;
Now using this function and look around our probable minimum:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data=Quiet@Table[{d,FindMaxima[d]},{d,150,175,1}];&#xD;
    data//ListLogPlot&#xD;
    TakeSmallestBy[data,Last,1]&#xD;
&#xD;
![enter image description here][9]&#xD;
&#xD;
Which also find 166. So that seems to be in agreement. Another [paper][10] found 0x5f375a86 which 16^^5f375a86 - magicconst = 167. So perhaps he/me is wrong with rounding somehow&#xD;
&#xD;
## Average error ##&#xD;
&#xD;
So far, we&amp;#039;ve been looking at maximum error possible, but what about minimising the average error? Since we&amp;#039;re using floating point numbers that can range over many many decades I would like to minimize the following integral of the error:&#xD;
&#xD;
    Integrate[relativeerror[2^s]^2,{s,0,2}]&#xD;
&#xD;
Note that I do not sample the domain x 1 to 4 linearly. Again we can run for large deviations from the magic constant:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data=Table[{d,Total[Table[With[{x=2^s},((1/Sqrt[x]-fastinvsqrt[x,d+magicconst])/(1/Sqrt[x]))^2],{s,0,2,0.00001}]]},{d,-250000,250000,10000}];&#xD;
    data//ListLogPlot&#xD;
    TakeSmallestBy[data,Last,1]&#xD;
&#xD;
![enter image description here][11]&#xD;
&#xD;
Let&amp;#039;s zoom in a bit more:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data=Table[{d,Total[Table[With[{x=2^s},((1/Sqrt[x]-fastinvsqrt[x,d+magicconst])/(1/Sqrt[x]))^2],{s,0,2,0.00001}]]},{d,-96000,-94000,20}];&#xD;
    data//ListLogPlot&#xD;
    TakeSmallestBy[data,Last,1]&#xD;
&#xD;
![enter image description here][12]&#xD;
&#xD;
And zooming a bit more and using a smaller &amp;#039;integration&amp;#039; steps:&#xD;
&#xD;
    Dynamic[d]&#xD;
    data=Table[{d,Total[Table[With[{x=2^s},((1/Sqrt[x]-fastinvsqrt[x,d+magicconst])/(1/Sqrt[x]))^2],{s,0,2,0.00000005}]]},{d,-94900,-94800,1}];&#xD;
    data[[All,2]]=Rescale[data[[All,2]]];&#xD;
    ListPlot[data,PlotRange-&amp;gt;All]&#xD;
    TakeSmallestBy[data,Last,1]&#xD;
&#xD;
![enter image description here][13]&#xD;
&#xD;
The lowest value happens at magicconstant - 94863:&#xD;
&#xD;
    LogLogPlot[{relativeerror[x,magicconst],relativeerror[x,magicconst-94863]},{x,0.01,100000},Frame-&amp;gt;True,PlotRangePadding-&amp;gt;None,PlotRange-&amp;gt;{10^-5,1},PlotPoints-&amp;gt;1200,MaxRecursion-&amp;gt;3]&#xD;
    LogLinearPlot[{relativeerror[x,magicconst]^2,relativeerror[x,magicconst-94863]^2},{x,1,4},Frame-&amp;gt;True,PlotRangePadding-&amp;gt;None,PlotRange-&amp;gt;All,PlotPoints-&amp;gt;1200,MaxRecursion-&amp;gt;3]&#xD;
&#xD;
![enter image description here][14]&#xD;
&#xD;
Here (in orange) the average (square) relative error is better as compared to the original constant. &#xD;
&#xD;
Hope you enjoyed this little exploration of using C code inside Mathematica and to optimize low-level algorithms interactively using Mathematica&amp;#039;s library functionality and plotting functionality. The original code includes a single Newton iteration to further hone in to the correct answer, the plots I&amp;#039;ve showed are for a single iteration. Other people have optimized the constant for not a single iteration or two iterations So there are different constants out there. And, since the values are always under-estimated, the Newton iteration can also be modified to account for this. &#xD;
&#xD;
&#xD;
  [1]: https://en.wikipedia.org/wiki/Fast_inverse_square_root&#xD;
  [2]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.36.58.png&amp;amp;userId=73716&#xD;
  [3]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.40.10.png&amp;amp;userId=73716&#xD;
  [4]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.41.11.png&amp;amp;userId=73716&#xD;
  [5]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.43.40.png&amp;amp;userId=73716&#xD;
  [6]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.49.01.png&amp;amp;userId=73716&#xD;
  [7]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.47.42.png&amp;amp;userId=73716&#xD;
  [8]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.50.33.png&amp;amp;userId=73716&#xD;
  [9]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at01.54.12.png&amp;amp;userId=73716&#xD;
  [10]: https://cs.uwaterloo.ca/~m32rober/rsqrt.pdf&#xD;
  [11]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at02.04.47.png&amp;amp;userId=73716&#xD;
  [12]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at02.05.39.png&amp;amp;userId=73716&#xD;
  [13]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at02.07.26.png&amp;amp;userId=73716&#xD;
  [14]: http://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2017-05-27at02.13.55.png&amp;amp;userId=73716</description>
    <dc:creator>Sander Huisman</dc:creator>
    <dc:date>2017-05-27T00:25:47Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1037730">
    <title>Performance tuning in Wolfram Language</title>
    <link>https://community.wolfram.com/groups/-/m/t/1037730</link>
    <description>*NOTE:  Please see the original version of this post [**HERE**][1]. Cross-posted here per suggestion of  [@Vitaliy Kaurov][at0].*&#xD;
&#xD;
----------&#xD;
&#xD;
&#xD;
Since Mathematica is a symbolic system, with symbolic evaluator much more&#xD;
general than in numerically-based languages, it is not surprising that performance-tuning can be &#xD;
more tricky here. There are many techniques, but they can all be understood &#xD;
from a single main principle. It is:&#xD;
&#xD;
   *Avoid full Mathematica symbolic evaluation process as much as possible.*&#xD;
   &#xD;
All techniques seem to  reflect some facet of it. The main idea here is that most of the &#xD;
time, a slow Mathematica program is such because many Mathematica functions are very general. This &#xD;
generality is a great strength, since it enables the language to support better and more powerful abstractions, but in many places in the program such generality, used without care, can be a (huge) overkill. &#xD;
&#xD;
I won&amp;#039;t be able to give many illustrative examples in the limited space, but they can be found in &#xD;
several places, including some WRI technical reports (Daniel Lichtblau&amp;#039;s &#xD;
one on efficient data structures in Mathematica comes to mind), a very good&#xD;
book of David Wagner on Mathematica programming, and most notably, many Mathgroup&#xD;
posts. I also discuss a limited subset of them in  [my book][3]. I will supply more references soon.&#xD;
&#xD;
Here are a few most common ones (I only list those available within Mathematica &#xD;
language itself, not mentioning CUDA \ OpenCL, or links to other languages, which are &#xD;
of course also the possibilities):&#xD;
&#xD;
1.	*Push as much work into the kernel at once as possible, work with as large &#xD;
chunks of data at a time as possible, without breaking them into pieces*&#xD;
&#xD;
	1.1. Use built-in functions whenever possible. Since they are implemented &#xD;
	in the kernel, in a lower-level language (C), they are typically (but not always!)&#xD;
	much faster	than user-defined ones solving the same problem. The more specialized&#xD;
	version of a built-in function you are able to use, the more chances you have for a speed-up.&#xD;
&#xD;
	1.2. Use functional programming (`Map, Apply`, and friends). Also, use pure functions&#xD;
	in `#-&amp;amp;` notation when you can, they tend to be faster than Function-s with named&#xD;
	arguments or those based on patterns (especially for not computationally-intensive&#xD;
	functions mapped on large lists).&#xD;
   &#xD;
	1.3. Use structural and vectorized operations (`Transpose, Flatten, &#xD;
	Partition, Part` and friends), they are even faster than functional.&#xD;
   &#xD;
	1.4. Avoid using procedural programming (loops etc), because this programming&#xD;
	style tends to break large structures into pieces (array indexing etc).&#xD;
	This pushes larger part of the computation outside of the kernel and makes it slower. &#xD;
&#xD;
   	&#xD;
    &#xD;
   &#xD;
2. *Use machine-precision whenever possible*&#xD;
&#xD;
	2.1. Be aware and use Listability of built-in numerical functions, applying them to &#xD;
        large lists of data rather than using `Map` or loops.&#xD;
		&#xD;
	2.2. Use `Compile`, when you can. Use the new capabilities of `Compile`, such as `CompilationTarget-&amp;gt;&amp;#034;C&amp;#034;`,&#xD;
	and making our compile functions parallel and Listable.&#xD;
	&#xD;
	2.3. Whenever possible, use vectorized operations (`UnitStep, Clip, Sign, Abs`, etc)&#xD;
	inside `Compile`, to realize &amp;#034;vectorized control flow&amp;#034; constructs such as `If`, so that &#xD;
	you can avoid 	explicit loops (at least as innermost loops) also inside `Compile`. This &#xD;
	can move you 	in speed from Mathematica byte-code to almost native C speed, in some cases.&#xD;
&#xD;
       2.4. When using `Compile`, make sure that the compiled function doesn&amp;#039;t bail out to non-compiled evaluation.  See examples [in this MathGroup thread][4].&#xD;
&#xD;
3. *Be aware that Lists are implemented as arrays in Mathematica*&#xD;
&#xD;
    3.1. Pre-allocate large lists&#xD;
	&#xD;
	3.2. Avoid `Append, Prepend, AppendTo` and `PrependTo` in loops, for building &#xD;
	lists etc (because they copy entire list to add a single element, which leads&#xD;
	to quadratic rather than linear complexity for list-building)&#xD;
	&#xD;
	3.3. Use linked lists (structures like `{1,{2,{3,{}}}}` ) instead of plain lists&#xD;
	for list accumulation in a program. The typical idiom is `a = {new element, a}`.&#xD;
	Because a is a reference, a single assignment is constant-time.&#xD;
	&#xD;
	3.4. Be aware that pattern-matching for sequence patterns (BlankSequence, &#xD;
	BlankNullSequence) is also based on Sequences being arrays. Therefore, a rule&#xD;
	`{fst_,rest___}:&amp;gt;{f[fst],g[rest]}` will copy the entire list when applied. In particular, don&amp;#039;t&#xD;
   use recursion in a way which may look natural in other languages. If you want to use recursion on lists, first convert your lists to linked lists.&#xD;
	&#xD;
4.  *Avoid inefficient patterns, construct efficient patterns*&#xD;
&#xD;
	4.1. Rule-based programming can be both very fast and very slow, depending on how &#xD;
	you build your structures and rules, but in practice it is easier to inadvertently &#xD;
	make it slow. It will be slow for rules which force the pattern-matcher to make many &#xD;
	a priory doomed matching attempts, for example by under-utilizing each run of the &#xD;
	pattern-matcher through a long list (expression). Sorting elements is a good example:&#xD;
	`list//.{left___,x_,y_,right___}/;x&amp;gt;y:&amp;gt;{left,y,x,right}` - has a cubic complexity in the&#xD;
	size of the list (explanation is e.g. [here][5]).&#xD;
	&#xD;
	4.2. Build efficient patterns, and corresponding  structures to store your data, making &#xD;
	pattern-matcher to waste as little time on false matching attempts as possible.&#xD;
	&#xD;
	4.3. Avoid using patterns with  computationally intensive conditions or tests. The &#xD;
    pattern-matcher will give you the most speed when  patterns	are mostly syntactic in &#xD;
	nature (test structure, heads, etc). Every time when condition `(/;)` or pattern test `(?)`&#xD;
	is used, for every potential match, the evaluator is invoked by the pattern-matcher,&#xD;
	and this slows it down.&#xD;
	&#xD;
5.  *Be aware of immutable nature of most Mathematica built-in functions*&#xD;
    &#xD;
    Most Mathematica built-in functions which process lists create a copy of an original list and &#xD;
    operate on that copy. Therefore, they may have a linear time (and space) complexity in the &#xD;
    size of the original list, even if they modify a list in only a few places. One universal &#xD;
    built-in function that does not create a copy, modifies the original expression and does not &#xD;
    have this issue, is `Part`.&#xD;
  &#xD;
    5.1. Avoid using most list-modifying built-in functions for a large number of&#xD;
    small independent list modifications, which can not be formulated as a single step&#xD;
    (for example, `NestWhile[Drop[#,1]&amp;amp;,Range[1000],#&amp;lt;500&amp;amp;]` )&#xD;
&#xD;
    5.2. Use extended functionality of `Part` to extract and modify a large number of &#xD;
	list (or more general expression) elements at the same time. This is very fast,&#xD;
	and not just for packed numerical arrays (`Part` modifies the original list).&#xD;
	&#xD;
	5.3. Use `Extract` to extract many elements at different levels at once, passing &#xD;
	to it a possibly large list of element positions.&#xD;
	&#xD;
	&#xD;
6. *Use efficient built-in data structures*&#xD;
&#xD;
    The following internal data structures are very efficient and can be used in &#xD;
	many more situations than it may appear from their stated main purpose. Lots of such examples can be found by searching the Mathgroup archive, particularly contributions of Carl Woll. &#xD;
&#xD;
	6.1. Packed arrays&#xD;
&#xD;
    6.2. Sparse arrays	&#xD;
	&#xD;
7. *Use hash - tables.* &#xD;
&#xD;
   Starting with version 10,  immutable associative arrays are available in Mathematica (Associations)&#xD;
&#xD;
7.1 Associations&#xD;
&#xD;
the fact that they are immutable does not prevent them to have efficient insertion and deletion of key-value pairs (cheap copies different from the original association by the presence, or absence, of a given key-value pair). They represent the idiomatic associative arrays in Mathematica, and have very good performance characteristics.&#xD;
&#xD;
For earlier versions,the following alternatives work pretty well, being based on internal Mathematica&amp;#039;s hash-tables:&#xD;
&#xD;
7.2. Hash-tables based on `DownValues` or `SubValues`&#xD;
	&#xD;
7.3. `Dispatch`	&#xD;
	&#xD;
8. *Use element - position duality*&#xD;
&#xD;
	Often you can write faster functions to work with positions of elements rather than &#xD;
	elements themselves, since positions are integers (for flat lists). This can give you &#xD;
	up to an order of magnitude speed-up, even compared to generic built-in functions &#xD;
	(`Position` comes to mind as an example).&#xD;
	&#xD;
9.  *Use Reap - Sow*&#xD;
&#xD;
    `Reap` and `Sow` provide an efficient way of collecting intermediate results, and generally &#xD;
	&amp;#034;tagging&amp;#034; parts you want to collect, during the computation. These commands also go well&#xD;
	with functional programming.&#xD;
	&#xD;
10.  *Use caching, dynamic programming, lazy evaluation*&#xD;
&#xD;
    10.1. Memoization is very easily implemented in Mathematica, and can save a lot of execution &#xD;
	time for certain problems.&#xD;
	&#xD;
	10.2. In Mathematica, you can implement more complex versions of memoization, where you can &#xD;
	define functions (closures) at run-time, which will use some pre-computed parts in their&#xD;
	definitions and therefore will be faster.&#xD;
	&#xD;
	10.3. Some problems can benefit from lazy evaluation. This seems more relevant to memory - &#xD;
	efficiency, but can also affect run-time efficiency. Mathematica&amp;#039;s symbolic constructs make &#xD;
	it easy to 	implement.&#xD;
	&#xD;
	&#xD;
A successful performance - tuning process usually employs a combination of these techniques, &#xD;
and you will need some practice to identify cases where each of them will be beneficial.&#xD;
&#xD;
&#xD;
  [1]: http://mathematica.stackexchange.com/a/29351&#xD;
  [2]: https://groups.google.com/d/topic/comp.soft-sys.math.mathematica/XOXapJm_Q1Q/discussion&#xD;
  [3]: http://www.mathprogramming-intro.org/&#xD;
  [4]: https://groups.google.com/d/topic/comp.soft-sys.math.mathematica/XOXapJm_Q1Q/discussion&#xD;
  [5]: http://www.mathprogramming-intro.org/book/node355.html&#xD;
&#xD;
 [at0]: http://community.wolfram.com/web/vitaliyk</description>
    <dc:creator>Leonid Shifrin</dc:creator>
    <dc:date>2017-03-22T20:05:20Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/286203">
    <title>Slow Summation of values produced by recursive function</title>
    <link>https://community.wolfram.com/groups/-/m/t/286203</link>
    <description>Hi,
I have defined a recursive function using memoization

    f[t_,x_]:=f[t,x]= ......

then i need to execute some sums like this

    marg = -Sum[j*f[0, j], {j, -100, 100}];
this sum takes up to 0.85 sec in order to be executed, depending on the function (actually I have more recursive functions, and i use one sum like the previous one for each. Hence, my algorithm speed overall is too slow, resulting in 4,50 seconds about).

I tried two alternative methods to improve speed but unsuccesfully

1)  using tables, and then function total, like this


     pinakas = Table[i*f[0, i], {i, 0, 100}]
     Total[pinakas]

2) using for function instead of Sum

    s2=0
    For[

    i=0,i&amp;lt;=100,i++,

    s2=s2+f[0,?]

    ]

All methods (i guess thats logical) yield the same times more or less. I have setup my algorithm in an excel file, and while serial, my algorithm is superfast. I cannot understand why, but if I print all values needed from my function, print is instant (which means that each f[0,i] is really fast calculated) but this sum is so slow. 

I though that It would be wise to limit precision somehow in my f[0,i] values, since I only need 3-4 digits, but I do not know how to exactly perform that. I even used decimals instead of integers (1.0 instead of 1 for example) as suggested in various guides, but this resulted in a decrease of speed.

So here I am, asking for your assistance.. unfortunately I cannot provide community with actual code, but I would appreciate any tip or assistance.

Regards</description>
    <dc:creator>Tom Zinger</dc:creator>
    <dc:date>2014-07-02T15:14:19Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1855244">
    <title>The Most Convenient Keyboard Shortcuts Ever</title>
    <link>https://community.wolfram.com/groups/-/m/t/1855244</link>
    <description>Here are two simple but extremely convenient keyboard shortcuts that I&amp;#039;ve used for years. &#xD;
&#xD;
 - This post is a favor to all my friends who type slowly (like me)&#xD;
 - These shortcuts simply create a pair of brackets containing a template placeholder as the current new selection&#xD;
 - Essentially, it&amp;#039;s just a stripped-down version of the bulky (Command + Shift + K + Up/Down Arrow + Enter) completion&#xD;
&#xD;
**Favorite Shortcut #1:** &#xD;
Autocomplete single brackets by pressing `CommandKey + [`&#xD;
&#xD;
![enter image description here][1]&#xD;
&#xD;
**Favorite Shortcut #2:** Autocomplete part brackets by pressing `CommandKey + ]`&#xD;
&#xD;
![enter image description here][2]&#xD;
&#xD;
## How to set them up ##&#xD;
&#xD;
On MacOS, first make a backup of the following file, in case you break it:&#xD;
&#xD;
    FileNameJoin[{$InstallationDirectory, &amp;#034;SystemFiles/FrontEnd/TextResources/Macintosh/KeyEventTranslations.tr&amp;#034;}];&#xD;
&#xD;
On my machine this path resolves to: *&amp;#034;/Applications/Mathematica.app/Contents/SystemFiles/FrontEnd/TextResources/Macintosh/KeyEventTranslations.tr&amp;#034;*&#xD;
&#xD;
Then, preferably in a non-Mathematica editor (e.g. Sublime), open the above file and copy-and-paste these following code into the list inside `EventTranslations`. For the first shortcut:&#xD;
&#xD;
    Item[KeyEvent[&amp;#034;[&amp;#034;,Modifiers-&amp;gt;{Command}],FrontEndExecute[{FrontEnd`NotebookWrite[FrontEnd`InputNotebook[],&amp;#034;[\[SelectionPlaceholder]]&amp;#034;],FrontEndToken[&amp;#034;MovePreviousPlaceHolder&amp;#034;]}]]&#xD;
    &#xD;
And for the second (of course making sure they are separated by a comma):&#xD;
&#xD;
    Item[KeyEvent[&amp;#034;]&amp;#034;,Modifiers-&amp;gt;{Command}],FrontEndExecute[{FrontEnd`NotebookWrite[FrontEnd`InputNotebook[],&amp;#034;\[LeftDoubleBracket]\[SelectionPlaceholder]\[RightDoubleBracket]&amp;#034;],FrontEndToken[&amp;#034;MovePreviousPlaceHolder&amp;#034;],FrontEndToken[&amp;#034;MovePreviousPlaceHolder&amp;#034;]}]]&#xD;
    &#xD;
Finally, restart Mathematica, and presto, they should both be working. And to remove the shortcuts, simply remove those items or replace the .tr file with the backup.&#xD;
&#xD;
  [1]: https://community.wolfram.com//c/portal/getImageAttachment?filename=own.gif&amp;amp;userId=900170&#xD;
  [2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=part.gif&amp;amp;userId=900170</description>
    <dc:creator>Michael Sollami</dc:creator>
    <dc:date>2020-01-08T20:42:08Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1857499">
    <title>Wolfram Mathematica does not evaluate at all</title>
    <link>https://community.wolfram.com/groups/-/m/t/1857499</link>
    <description>Hi, the title tells everything, I do not know why it doesn&amp;#039;t evaluate a thing. Even if I write down 5+6 and press shift+ctrl as usually it does nothing it just moves to next line and that&amp;#039;s all. I installed it a month ago and used it once and it worked very well as I remember. I deleted it and installed again previously but of course it had no effect at all. Do you have any suggestions?&#xD;
Thank you.&#xD;
&#xD;
Other informations: Wolfram Mathematica version 12.0&#xD;
OS: Windows 10</description>
    <dc:creator>Terezija Kre?i?</dc:creator>
    <dc:date>2020-01-13T17:17:39Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/1931315">
    <title>CodeParser and CodeInspector</title>
    <link>https://community.wolfram.com/groups/-/m/t/1931315</link>
    <description>[![enter image description here][2]][1]&#xD;
&#xD;
&amp;amp;[Wolfram Notebook][3]&#xD;
&#xD;
  [1]: https://youtu.be/rOa5IntICFA&#xD;
  [2]: https://community.wolfram.com//c/portal/getImageAttachment?filename=ScreenShot2020-04-09at12.54.33PM.png&amp;amp;userId=11733&#xD;
  [3]: https://www.wolframcloud.com/obj/afe2a2fb-ee55-4df5-a6fb-9bc16dd08af7</description>
    <dc:creator>Brenton Bostick</dc:creator>
    <dc:date>2020-04-09T15:04:38Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/175914">
    <title>Mathematica  - Mac or PC?</title>
    <link>https://community.wolfram.com/groups/-/m/t/175914</link>
    <description>Hi,

After a long time dithering, I&amp;#039;ve decided to buy a copy of Mathematica 9 Home Edition.  However, I&amp;#039;m not sure whether to go for the Windows or Macintosh version and would like to elicit some guidance to help me choose.  

I intend to mainly use Mathematica for mucking around with maths, some education for my children (age range 8 yrs to 13 yrs) and a fair bit of physics / astronomy simulation (I&amp;#039;m a professional systems engineer but my degree&amp;#039;s in astrophysics and I&amp;#039;d like to start playing around with it before I forget everything!).

I&amp;#039;ve got a rather elderly Dell (4 GiB RAM) running Windows 7 Ultimate and equipped with a 23&amp;#034; monitor, and I also have a recently acquired 21&amp;#034; iMac mid-2011 model with 8 GiB RAM; I bought the latter primarily for my wife to use and it&amp;#039;s my first foray into the Mac world (...[i] well, not quite true, I used a Mac SE for a bit at work decades ago and found Hypercard quite interesting[/i]).  I&amp;#039;m unlikely to upgrade either machine within the next 12 months.

Are there any differences between the Win and Mac implementations that might sway me one way or the other?   Or any portability considerations that might pop up in the future (eg, I&amp;#039;m going to get my children (well, that&amp;#039;s my story and I&amp;#039;m sticking to it) a Raspberry Pi, I occasionally steal my wife&amp;#039;s iPad mini and I use an Android phone) ... 

Thank you for your consideration.  

Hoping everyone had a good Christmas and has a Good New Year.

Stuart</description>
    <dc:creator>Stuart Bruff</dc:creator>
    <dc:date>2013-12-27T13:27:39Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/93435">
    <title>This OpenCL code seems to be leaking memory. Any ideas?</title>
    <link>https://community.wolfram.com/groups/-/m/t/93435</link>
    <description>Hello all,

I&amp;#039;ve been playing around with OpenCL and I&amp;#039;ve run into a problem that I can&amp;#039;t pin down. When running this n-body simulation, the amount of memory in use gradually increases with every time step (until I run out completely). I&amp;#039;ve tried using Bytecount[] on every variable that I can think of, and none of them seem to be the culprit.

Anyway, the OpenCL code in question is here:
[code]__kernel void nbody_kern(
	float timeStep,
	float eps,
	__global float4* position1,
	__global float4* velocity1,
	__global float4* acceleration1,
	__global float4* position2,
	__global float4* velocity2,
	__global float4* acceleration2,
	__local float4* localPosition
) {
	const float4 dt = (float4)(timeStep,timeStep,timeStep,0.0f);

	int idxGlobal = get_global_id(0);
	int idxLocal = get_local_id(0);

	int globalSize = get_global_size(0);
	int localSize = get_local_size(0);
	int blocks = globalSize / localSize;
	
	float4 currentPosition = position1[idxGlobal];
	float4 currentVelocity = velocity1[idxGlobal];
	float4 currentAcceleration = acceleration1[idxGlobal];
	
	float4 newPosition = (float4)(0.0f,0.0f,0.0f,0.0f);
	float4 newVelocity = (float4)(0.0f,0.0f,0.0f,0.0f);
	float4 newAcceleration = (float4)(0.0f,0.0f,0.0f,0.0f);
	
	for(int currentBlock = 0; currentBlock &amp;lt; blocks; currentBlock++)
	{
		localPosition[idxLocal] = position1[currentBlock * localSize + idxLocal];
		barrier(CLK_LOCAL_MEM_FENCE);
		for(int idx = 0; idx &amp;lt; localSize; idx++)
		{
			float4 dir = localPosition[idx] - currentPosition;
			float invRadius = rsqrt(dir.x * dir.x + dir.y * dir.y + dir.z * dir.z + eps);
			float magnitude = localPosition[idx].w * invRadius * invRadius * invRadius;
			newAcceleration += magnitude * dir;
		}
		barrier(CLK_LOCAL_MEM_FENCE);
	}
	
	// leapfrog integration
	newPosition = currentPosition + currentVelocity * dt + 0.5f * currentAcceleration * dt * dt;
	newVelocity = currentVelocity + 0.5f * (currentAcceleration + newAcceleration) * dt;
	
	position2[idxGlobal] = newPosition;
	velocity2[idxGlobal] = newVelocity;
	acceleration2[idxGlobal] = newAcceleration;
}[/code] 
and the Mathematica code is here:[mcode]initialVelocity[pt_] := Module[
  {y, v0, \[Theta]},
  y = Norm[pt[[1 ;; 3]]]/(2 rd);
  v0 = 4*\[Pi]*\[CapitalSigma]0*rd*
    y^2 (BesselI[0, y]*BesselK[0, y] - BesselI[1, y]*BesselK[1, y]);
  \[Theta] = ArcTan[pt[[1]], pt[[2]]];
  {-v0 Sin[\[Theta]], v0 Cos[\[Theta]], 0.0, 0.0} + 
   RandomVariate[NormalDistribution[0, .001], 4]
  ]

Needs[&amp;#034;OpenCLLink`&amp;#034;];
source = {&amp;#034;D:\\Google Drive\\Mathematica\\nbody.cl&amp;#034;};

stepSimulation = OpenCLFunctionLoad[
   source,
   &amp;#034;nbody_kern&amp;#034;,
   {
    &amp;#034;Float&amp;#034;,
    &amp;#034;Float&amp;#034;,
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Input&amp;#034;},
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Input&amp;#034;},
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Input&amp;#034;},
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Output&amp;#034;},
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Output&amp;#034;},
    {&amp;#034;Float&amp;#034;, _, &amp;#034;Output&amp;#034;},
    {&amp;#034;Local&amp;#034;, &amp;#034;Float&amp;#034;}
    },
   256, &amp;#034;ShellOutputFunction&amp;#034; -&amp;gt; Print
   ];

dt = .01;
eps = .0001;
rd = 1.0;
\[CapitalSigma]0 = 0.3;
len = 2^14;

particles = (RandomVariate[ExponentialDistribution[rd]]*{Cos[#], 
       Sin[#], 0.0, 0.0}) &amp;amp; /@ RandomReal[{0, 2 Pi}, len];
particles[[All, 4]] = 1.0/len;
velocity = initialVelocity /@ particles;
acceleration = Array[{0.0, 0.0, 0.0, 0.0} &amp;amp;, len];

position1 = OpenCLMemoryLoad[particles, &amp;#034;Float&amp;#034;];
velocity1 = OpenCLMemoryLoad[velocity, &amp;#034;Float&amp;#034;];
acceleration1 = OpenCLMemoryLoad[acceleration, &amp;#034;Float&amp;#034;];

position2 = OpenCLMemoryAllocate[&amp;#034;Float&amp;#034;, {len, 4}];
velocity2 = OpenCLMemoryAllocate[&amp;#034;Float&amp;#034;, {len, 4}];
acceleration2 = OpenCLMemoryAllocate[&amp;#034;Float&amp;#034;, {len, 4}];

pr = 8;
memList = {MemoryInUse[]};
Graphics3D[{
  PointSize[Small],
  Point[Dynamic[Refresh[
     AppendTo[memList, MemoryInUse[]];
     stepSimulation[dt, eps, position1, velocity1, acceleration1, 
      position2, velocity2, acceleration2, 256*4, len];
     stepSimulation[dt, eps, position2, velocity2, acceleration2, 
      position1, velocity1, acceleration1, 256*4, len];
     OpenCLMemoryGet[position1][[All, 1 ;; 3]],
     UpdateInterval -&amp;gt; 0]]
   ]}, PlotRange -&amp;gt; {{-pr, pr}, {-pr, pr}, {-pr/4, pr/4}}, 
 ImageSize -&amp;gt; 1000
 ]
Dynamic[ListLinePlot[memList]]
[/mcode]
As far as I can tell, the code does what it&amp;#039;s supposed to and I&amp;#039;m generally pleased with the results. This is what I get after a few steps:
[img=width: 400px; height: 334px;]http://i.imgur.com/hQFbPZO.png[/img]
However, the memory problem limits how long I can run this thing for. This plot shows the amount of memory in use with respect to the number of steps completed in the simulation.
[img=width: 360px; height: 209px;]http://i.imgur.com/SGWx0aP.png[/img]

The only way I&amp;#039;ve been able to free up all that memory is by quitting the kernel, which is hardly ideal. I&amp;#039;m guessing that I&amp;#039;m just missing some important aspect of OpenCL programming. If anyone is more familiar with this stuff and has some ideas, I&amp;#039;d be thrilled to hear them.</description>
    <dc:creator>Richard Hennigan</dc:creator>
    <dc:date>2013-08-09T17:18:48Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/159073">
    <title>Help needed with code optimization in Manipulate</title>
    <link>https://community.wolfram.com/groups/-/m/t/159073</link>
    <description>I&amp;#039;m trying to build an interactive dynamic presentation with [b]Manipulate[/b] about the electric field lines generated by an electric dipole (couple of charges).
In my plan the user should be able to move the two charges generating the field (through a locator) and there would be a third locator for evaluating the field in that point (say point P). Moreover there will be a specific field line passing through that point P.

I&amp;#039;ve managed to write the code, but it&amp;#039;s [b]extremely slow[/b].
The problem seems to be that when I move the point P everything is recalculated within the Manipulate expression, even the field lines, that aren&amp;#039;t actually affected by the position of the point P and that requires some time machine for Mathematica&amp;#039;s end-front to draw the plot (also because the field lines are set to start/end in a specific - user controlled - set of points around the charges).

So how could I let Mathematica know that only some pieces of code must be re-evaluated when interactively moving some single control (i.e. a locator) and other parts need not?
Browsing the documentation I understand that this should be possible, but it&amp;#039;s not easy for me to understand the proper command to use ([i][b]Hold[/b][/i]? [i][b]Refresh[/b][/i]?) and the structure to give to the Manipulate expression. 

So if some expert could give me some advice on how to optimize my code to make the presentation much more responsive to the user&amp;#039;s interaction I&amp;#039;d be very grateful.

To be more specific here&amp;#039;s the (slow) code I&amp;#039;ve come up with till now. I understand that changing the position of the charges can be slow, as all the field lines should be recalculated, but simply changing the position of the P point should not be so slow as in this case the other field lines needn&amp;#039;t be recalculated.[mcode]Manipulate[
 DynamicModule[{xPt, yPt, xq1, yq1, xq2, yq2, r, r1, r2, Emag, Emag1, 
   Emag2, Ex, Ex1, Ex2, Ey, Ey1, Ey2, Exx, Eyy,(*qq1,qq2,*)qf, 
   VecE, \[Alpha]q, CenterP, FieldPts, EInt}, xPt = startPoint[[1]];
  yPt = startPoint[[2]];
  xq1 = q1pos[[1]];
  yq1 = q1pos[[2]];
  xq2 = q2pos[[1]];
  yq2 = q2pos[[2]];
  (*qq1=SourceCharge1;
  qq2=SourceCharge2;*)r1 = N[Sqrt[(xPt - xq1)^2 + (yPt - yq1)^2], 3];
  r2 = N[Sqrt[(xPt - xq2)^2 + (yPt - yq2)^2], 3];
  Emag1 = qq1/r1^2;
  Emag2 = qq2/r2^2;
  Ex1 = Emag1*(xPt - xq1)/r1;
  Ey1 = Emag1*(yPt - yq1)/r1;
  Ex2 = Emag2*(xPt - xq2)/r2;
  Ey2 = Emag2*(yPt - yq2)/r2;
  Exx = Ex1 + Ex2;
  Eyy = Ey1 + Ey2;
  VecE[x_, y_] := 
   VecE[x, y] = {(qq1 (x - xq1))/((x - xq1)^2 + (y - yq1)^2)^(3/
          2) + (qq2 (x - xq2))/((x - xq2)^2 + (y - yq2)^2)^(3/
          2), (qq1 (y - yq1))/((x - xq1)^2 + (y - yq1)^2)^(3/
          2) + (qq2 (y - yq2))/((x - xq2)^2 + (y - yq2)^2)^(3/2)};
  EInt[x_, y_] := 
   EInt[x, y] = \[Sqrt](((qq1 (x - 
               xq1))/((x - xq1)^2 + (y - yq1)^2)^(3/
              2) + (qq2 (x - xq2))/((x - xq2)^2 + (y - yq2)^2)^(3/
              2))^2 + ((qq1 (y - yq1))/((x - xq1)^2 + (y - yq1)^2)^(3/
              2) + (qq2 (y - yq2))/((x - xq2)^2 + (y - yq2)^2)^(3/
              2))^2);
  \[Alpha]q = ArcTan[(yq2 - yq1)/(xq2 - xq1)];
  CenterP = {{(xq1 + xq2)/2, (yq1 + yq2)/2}};
  FieldPts = 
   Flatten[{Table[{xq1 + d Cos[\[Alpha] + \[Alpha]q], 
       yq1 + d Sin[\[Alpha] + \[Alpha]q]}, {\[Alpha], 0, 
       2 \[Pi], \[Pi]/(3 2^s)}], 
     Table[{xq2 + d Cos[\[Alpha] + \[Alpha]q], 
       yq2 + d Sin[\[Alpha] + \[Alpha]q]}, {\[Alpha], 0, 
       2 \[Pi], \[Pi]/(3 2^s) If[qq2 == 0, 2 3 2^s, 
         Min[2 \[Pi], Abs[qq1]/Abs[qq2]]]}]}, 1];
  Show[{DensityPlot[
     0.1 + (2/\[Pi] ArcTan[EInt[x, y]])^ExCol, {x, -6 + offset, 
      6 - offset}, {y, -6 + offset, 6 - offset}, 
     ColorFunction -&amp;gt; GrayLevel, ColorFunctionScaling -&amp;gt; False, 
     ImageSize -&amp;gt; 800, GridLines -&amp;gt; Automatic, 
     BaseStyle -&amp;gt; Directive[Opacity[0.8]], 
     Epilog -&amp;gt; {Text[Style[P, 20, RGBColor[0, 0, 0], Bold, Italic], 
        startPoint, {0, 1.5}], 
       Text[Style[Subscript[q, 1], 24, RGBColor[0, 0, 0], Bold], 
        q1pos, {0, 2.5}], 
       Text[Style[Subscript[q, 2], 24, RGBColor[0, 0, 0], Bold], 
        q2pos, {0, 2.5}], 
       Arrowheads[.015], {Dashed, GrayLevel[0.25], 
        Line[{{VS*Ex2 + xPt, VS*Ey2 + yPt}, {VS*Exx + xPt, 
           VS*Eyy + yPt}}]}, {Dashed, GrayLevel[0.25], 
        Line[{{VS*Exx + xPt, VS*Eyy + yPt}, {VS*Ex1 + xPt, 
           VS*Ey1 + yPt}}]}, {RGBColor[0, 0.6, 0], 
        Disk[q1pos, .25]}, {Blue, Disk[q2pos, .25]}, {Black, 
        Disk[startPoint, .1]}, {Thin, RGBColor[0, 0.6, 0], 
        Arrow[{startPoint, {VS*Ex1 + xPt, VS*Ey1 + yPt}}]}, {Thin, 
        Blue, Arrow[{startPoint, {VS*Ex2 + xPt, 
           VS*Ey2 + yPt}}]}, {Thickness[0.0035], 
        RGBColor[0.5, 0.1, 0.1], 
        Arrow[{startPoint, {VS*Exx + xPt, VS*Eyy + yPt}}]}}], 
    If[field, 
     StreamPlot[
      VecE[x, y], {x, -6 + offset, 6 - offset}, {y, -6 + offset, 
       6 - offset}, 
      StreamPoints -&amp;gt; {{FieldPts -&amp;gt; 
          Directive[Thickness[Tiny], RGBColor[0.9, 0.5, 0.5]], 1}, 
        Fine, Scaled[1]}, StreamScale -&amp;gt; {0.08, 0.1, 0.0055}, 
      ImageSize -&amp;gt; 800], 
     StreamPlot[{0, 0}, {x, -6 + offset, 6 - offset}, {y, -6 + offset,
        6 - offset}, StreamPoints -&amp;gt; None, 
      StreamScale -&amp;gt; {0.08, 0.1, 0.0055}]], 
    StreamPlot[
     VecE[x, y], {x, -6 + offset, 6 - offset}, {y, -6 + offset, 
      6 - offset}, 
     StreamPoints -&amp;gt; {{{startPoint, RGBColor[0.5, 0.0, 0.1]}}}, 
     StreamScale -&amp;gt; 0.05, ImageSize -&amp;gt; 800, GridLines -&amp;gt; Automatic](*,
    StreamScale\[Rule]0.06*)}]], {{startPoint, {-0.4, 
    3}}, {-7, -7}, {7, 7}, 
  Locator}, {{q1pos, {-2, 0}}, {-7, -7}, {7, 7}, 
  Locator}, {{q2pos, {2, 0}}, {-7, -7}, {7, 7}, Locator}, 
 Grid[{{Control[{{qq1, 2, &amp;#034;\!\(\*SubscriptBox[\(q\), \(1\)]\)&amp;#034;}, -4, 
      4, .5, Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}], 
    Control[{{qq2, -2, &amp;#034;\!\(\*SubscriptBox[\(q\), \(2\)]\)&amp;#034;}, -4, 
      4, .5, Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}]}, {Control[{{d, 0.7, 
       &amp;#034;lines start distance form charges&amp;#034;}, 0.1, 4, 0.1, 
      Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}], 
    Control[{{s, 1, &amp;#034;lines density&amp;#034;}, 1, 4, 1, 
      Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}]}, {Control[{{VS, 13, &amp;#034;Vector Scale&amp;#034;}, 
      0, 25, 1, Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}], 
    Control[{{ExCol, 0.3, &amp;#034;Color Scale&amp;#034;}, 0, 1, 0.2, 
      Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}]}, {Control[{{offset, 0, 
       &amp;#034;Global range&amp;#034;}, -4, 4, 0.5, Appearance -&amp;gt; &amp;#034;Labeled&amp;#034;}], 
    Control[{{field, True, &amp;#034;Show Field lines&amp;#034;}, Checkbox}]}}, 
  Frame -&amp;gt; All], ControlPlacement -&amp;gt; Top][/mcode]Actually, if the code regarding the definition of the field lines starting points:[mcode]FieldPts = 
  Flatten[{Table[{xq1 + d Cos[\[Alpha] + \[Alpha]q], 
      yq1 + d Sin[\[Alpha] + \[Alpha]q]}, {\[Alpha], 0, 
      2 \[Pi], \[Pi]/(3 2^s)}], 
    Table[{xq2 + d Cos[\[Alpha] + \[Alpha]q], 
      yq2 + d Sin[\[Alpha] + \[Alpha]q]}, {\[Alpha], 0, 
      2 \[Pi], \[Pi]/(3 2^s) If[qq2 == 0, 2 3 2^s, 
        Min[2 \[Pi], Abs[qq1]/Abs[qq2]]]}]}, 1];[/mcode]is commented out, the presentation becomes much more quick (but the plot will show just the single field lines passing through the point P).
Here is a static image of my WIP presentation:

[img=width: 800px; height: 800px;]/c/portal/getImageAttachment?filename=DipoleElectricField_Temp.jpg&amp;amp;userId=150580[/img]</description>
    <dc:creator>Luca M</dc:creator>
    <dc:date>2013-11-23T20:43:30Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/190372">
    <title>Bottlenecking Code</title>
    <link>https://community.wolfram.com/groups/-/m/t/190372</link>
    <description>Hey guys,

So I&amp;#039;m working with a pretty large block of code and the thing is moving way slower than it should be in theory. Is there a way that I can monitor exactly where in the code Mathematica is working at any given moment?

Thanks bros!</description>
    <dc:creator>Jake Smith</dc:creator>
    <dc:date>2014-01-25T02:48:32Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/227021">
    <title>RAM and disk space are being filled up?</title>
    <link>https://community.wolfram.com/groups/-/m/t/227021</link>
    <description>Due to my reckless use of [i]Mathematica[/i], now I have very little free space on my hard drive.&#xD;
More precisely, the memory consumption appears to have occured due to execution of some unthinkable functions and quiting.&#xD;
&#xD;
The problem persists if I relaunch [i]Mathematica[/i], and even after rebooting.&#xD;
&#xD;
I regret my behavior, and I will be very grateful if someone tells me how can I free my space back.</description>
    <dc:creator>Sandu Ursu</dc:creator>
    <dc:date>2014-03-28T21:18:11Z</dc:date>
  </item>
  <item rdf:about="https://community.wolfram.com/groups/-/m/t/138207">
    <title>Ant Colony - Speeding up simulation &amp;amp; Extra Functionality</title>
    <link>https://community.wolfram.com/groups/-/m/t/138207</link>
    <description>Following up on Bernat&amp;#039;s posting here [url=http://community.wolfram.com/groups/-/m/t/136023?p_p_auth=2Af2XNsw]http://community.wolfram.com/groups/-/m/t/136023?p_p_auth=2Af2XNsw[/url], I attempted my first cut on simulating an ant colony hunting for food.
The code runs too slow, it processes 3.5 cycles (ticks) per second for 25 ants.

Would be very grateful for ideas on how to:[list=1]
[*]Improve performance of the code.
[*]Mathematica Functions/Ideas for adding diffusion to the pheromone field (represented by a matrix) without adding excessive performance cost (played with converting the matrix to an image &amp;gt; blurring &amp;gt; converting it back to a matrix) which adds and excessive time penalty.
[/list]Hope the code is clear enough. As written it takes 517 seconds in my PC.[mcode](*Define the world size*)
ymax = 200; xmax = 400;
(*Locate the colony somwhere in the world*)
nest = {RandomInteger[{1, xmax}], RandomInteger[{1, ymax}]};

maxAnts = 25;
ticks = 1;
maxSteps = 2000;
maxSpeed = 6;
maxAngle = 13 \[Pi]/16;
maxFoodPiles = 8;
smellRange = 12;
pheromoneDeposit = 1;
foodMultiplier = 1000;
pheromoneMultiplier = 10;
fieldCaptureInterval = 10;
discriminationFactor = 16;
noFood = 0;
withFood = 1;
antSymbol = \[Infinity];
evaporationRate = ConstantArray[(1 - 0.005), {xmax, ymax}];
pheromoneField = ConstantArray[0., {xmax, ymax}];
pheromoneField[[First@nest, Last@nest]] = 
  100000; (*Added a lot of pheromone at the nest to &amp;#039;help&amp;#039; the ants \
get back to the nest*)
foodField = ConstantArray[0., {xmax, ymax}];
(*Scatter the food in the world*)
foodPiles = 
  Transpose[{RandomInteger[{1, xmax}, maxFoodPiles], 
    RandomInteger[{1, ymax}, maxFoodPiles]}];
(foodField[[#[[1]], #[[2]]]] = 10) &amp;amp; /@ foodPiles;
(*We&amp;#039;ll record the history of the fields in these variables*)
pheromoneHistory = {pheromoneField};
foodHistory = {foodField};
(*Functions*)
(*Find out all positions that the ant will step as it moves \
forward/Keep ants within the world*)
calculateLoc[location_, direction_, steps_] := 
 Module[{loc, result = {}}, 
  Do[loc = Flatten[
     location + Round[{temp*Cos[direction], temp*Sin[direction]}]];
   loc = Min[#] &amp;amp; /@ Transpose[{loc, {xmax, ymax}}];
   loc = Max[#] &amp;amp; /@ Transpose[{loc, {1, 1}}];
   result = Append[result, loc], {temp, steps}];
  result]
(*Return the distribution probability of the direction that the ant \
will head to*)
(*It will add the smell of pheromones + food if no food is being \
carried *)
probDist[location_, direction_, hasFood_, range_, angle_, steps_] :=
 Module[{dist, total, bins, vals}, 
  dist = Flatten[
    Table[{direction + y , 
      Flatten[location + 
        Round[{x*Cos[direction + y ], 
          x*Sin[direction + y ]}]]}, {y, -angle/2, angle/2, 
      angle/steps}, {x, 1, range, 1}], 1];
  dist = DeleteCases[dist, 
    Alternatives[{_, {a_ /; a &amp;lt; 1, _}}, {_, {a_ /; 
        a &amp;gt; xmax, _}}, {_, {_, b_ /; b &amp;lt; 1}}, {_, {_, 
       b_ /; b &amp;gt; ymax}}]];
  (dist[[#, 
       2]] = ((1 - hasFood) foodMultiplier foodField[[
          First@dist[[#, 2]], Last@dist[[#, 2]]]] + 
        pheromoneField[[First@dist[[#, 2]], Last@dist[[#, 2]]]])) &amp;amp; /@
    Range[Length[dist]]; bins = Union[dist[[All, 1]]]; 
  vals = Cases[dist, {#, y_} -&amp;gt; y] &amp;amp; /@ bins; 
  vals = (Total[#] &amp;amp; /@ vals);
  total = Total[vals];
  If[total == 0, 
   UniformDistribution[{direction - angle/2, direction + angle/2}],
   EmpiricalDistribution[Rule[vals, bins]]]]
(*Routine Determines where the ant should head next*)
(*Also updates the pheromone field*)
update[agent[id_, symbol_, location_, direction_, hasFood_]] := 
 Module[{temp, dist, dir, speed, loc, path, status, foundDestination, 
   multiplier}, 
  dir = RandomVariate[
    probDist[location, direction, hasFood, smellRange, maxAngle, 
     discriminationFactor]];
  speed = RandomVariate[UniformDistribution[{1, maxSpeed}], 1];
  loc = calculateLoc[location, dir, speed];
  status = hasFood;
  If[status == noFood,
      multiplier = 1;
      foundDestination = 
       Select[loc, foodField[[#[[1]], #[[2]]]] &amp;gt; 0 &amp;amp;];
      If[Length@foundDestination != 0, status = withFood; 
       dir = dir + \[Pi]; multiplier = pheromoneMultiplier; 
       foundDestination = First@foundDestination; 
       foodField[[foundDestination[[1]], foundDestination[[2]]]] = 
        foodField[[foundDestination[[1]], foundDestination[[2]]]] - 
         1;],
      multiplier = pheromoneMultiplier;
      foundDestination = Cases[loc, nest];
      If[Length@foundDestination != 0, status = noFood; 
       dir = dir + \[Pi]; multiplier = 1;]
      ]
     (pheromoneField[[#[[1]], #[[2]]]] = 
       pheromoneField[[#[[1]], #[[2]]]] + 
        multiplier pheromoneDeposit) &amp;amp; /@ loc;
  
  agent[id, symbol, Last@loc, dir, status]]

update[agentList_List] := 
 Module[{set = update[#] &amp;amp; /@ agentList}, 
  pheromoneField = evaporationRate pheromoneField; 
  If[Mod[ticks, fieldCaptureInterval] == 0, 
   pheromoneHistory = Append[pheromoneHistory, pheromoneField]; 
   foodHistory = Append[foodHistory, foodField];]; ticks++; set]

(*Routines to display the ants in the animate section. Regretably \
can&amp;#039;t be used due to memory leak*)
display[agent[id_, symbol_, location_, direction_, hasFood_]] := 
 Text[Rotate[symbol, direction], location]
display[list_] := Module[{lst = display[#] &amp;amp; /@ list}, Graphics[lst]]

(*initialize ants*)
(*Initialize the colony - in which direction will the ants start \
walking out*)
ants = Table[
   agent[id, antSymbol, nest, 
    RandomVariate[UniformDistribution[{0, 2 \[Pi]}]], noFood], {id, 
    maxAnts}];

antHistory = NestList[update, ants, maxSteps]; // AbsoluteTiming

(*Did the ants eat the food? Check status of the food piles and how \
the pheromone field changed with time*)
foodField[[#[[1]], #[[2]]]] &amp;amp; /@ foodPiles
Manipulate[
 Show[ColorNegate@ImageRotate@Image@pheromoneHistory[[i]], 
  Graphics[{Red, PointSize[Large], Point[nest], PointSize[Medium], 
    Blue, Point[foodPiles]}]], {i, 1, Length@pheromoneHistory, 1}]

[/mcode][img=width: 800px; height: 557px;]/c/portal/getImageAttachment?filename=ants.gif&amp;amp;userId=78214[/img]</description>
    <dc:creator>Diego Zviovich</dc:creator>
    <dc:date>2013-10-12T21:08:11Z</dc:date>
  </item>
</rdf:RDF>

