Message Boards Message Boards

Solve a problem involving logical programming using "For" function?

Posted 7 years ago

I have a small programming problem to solve using Mathematica. Being new to the problem involving some sort of logical programming, looking for some initial help. I tried to write a script using the function “For”, which does not work at all. Would appreciate if someone can suggest an edit to the script or any other function more appropriate for solving such problems. Following is the simplified version of the problem I want to solve.

There are four pockets (say a, b, c and d) each having 1 dollar in the beginning of the experiment. Each of these pockets has a potential associated with it, which is a function of an independent variable V (say Fa = 3V, Fb = 4V etc). On varying the independent variable V, the potentials for each pocket take distinguished trajectories. Now the condition is that as the difference between two potentials exceeds a fixed constant, all the money which lower potential pocket has, is transferred to the one with higher potential pocket. For example, if this constant for pocket a & b is 5, the 1 dollar of a will be transferred to pocket b, as soon as Fa-Fb >= 5. Similarly, now 2 dollars of b will be transferred to another pocket c when Fc - Fb touches a fixed threshold difference. This redistribution of 4 dollars will continue with the variation of parameter V.

I want to solve this problem using Mathematica, so that I can have the distribution of the total $ 4 among four pockets as a function of parameter V. Thanks in advance

The small script which I tried is as follows. Attached is the *.nb file for this script.

Fa = 3*V;
Fb = 4*V;
Fc = 5*V;
Fd = 6*V;

For[a = 1; b = 1; c = 1; 
 d = 1, {Fb - Fa > 5, b == b + a; a = 0}; {Fc - Fb > 7, c == c + b; 
  b == 0}; {Fd - Fc > 8, d == c + d; c == 0}, {Do[V, {V, 1, 20, 1}], 
  Plot[{a, b, c, d}, {V, 1, 20}]}]
Attachments:
POSTED BY: S G
Posted 7 years ago

This?

Fa = 3*V; Fb = 4*V; Fc = 5*V; Fd = 6*V;
a = 1; b = 1; c = 1; d = 1;
matrix = Table[
   If[Fb - Fa > 5, b = b + a; a = 0];
   If[Fc - Fb > 7, c = c + b; b = 0];
   If[Fd - Fc > 8, d = c + d; c = 0];
   {a, b, c, d}, {V, 20}];
ListPlot[Transpose[matrix], Joined->True, PlotLegends->{"a", "b", "c", "d"}]

enter image description here

There is a lot going on in that for someone who is new to Mathematica. {} and ; mean very different things in Mathematica than they do in other more "normal" programming languages. Search for some of those words and operators in the help system, see if you can try to understand why I did some of the things the way that I did, click on "Options and Details" in the help page to see more information.

POSTED BY: Bill Simpson
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract