开发者

Loop in SWI-PROLOG

I have to create a program, to simulate energy exchange between particles, let me explaine: i have to create a list of 1000 particles each particle begining with energy = 5 quanta, then I have to randomly select 2 particle (P1 and P2) to exchange one quanta of energy (E1-1 and E2+1) this would be 1开发者_运维百科 exchange, i have to do n exchange until reach the boltzmann distribuction.

keeping in mind that a particle cannot exchange energy with itself, and a particle cannot have energy < 1 quanta.

%Create a list (Particle/energ) [1/5,2/5,3/5...1000/5].

from_to2(P1, P1000, List) :- 
bagof(N/5, between(P1,P1000,N), List),!. 
from_to2(_,_,[]).

%Exchange 1 quanta of energy between to particle: E1+1 , E2-1

energexchange(L1,L2):- 
choose(L1,Px/Ex), 
delete(Px/Ex,L1,Listsem1), 
choose(Listsem1,Py/Ey), 
delete(Py/Ey,Listsem1,Listsem2), 
Ex > 1, Ex2 is Ex - 1, add(Px/Ex2,Listsem2,Listcom1), 
Ey2 is Ey + 1, add(Py/Ey2,Listcom1,L2).

example: ?-from_to2(1,1000,L), energexchange(L,L2). gives L2= [3/4,1/6,2/5,4/5,5/5...1000/5]

L2 is the first exchange now I need to use L2 in the next exchange, energexchange(L2,L3). to do the second exchange and so on...

What should I do to repeat energexchange 1000 times without counting the fails (when Ex=1)?


Think declaratively: What are N exchanges? If N=0, no exchange at all takes place. Otherwise (implicitly assuming N can only take non-negative values), one exchange takes place, and N-1 exchanges take place after that. The code could look similar to:

n_exchanges(0, L, L) :- !.
n_exchanges(N0, L0, L) :-
        one_exchange(L0, L1),
        N1 is N0 - 1,
        n_exchanges(N1, L1, L).


I don't think Prolog supports looping outright, but you can use recursion to accomplish it. Something like

doexchanges(X) :- energyexchange ...

doexchanges(0) :- some sort of stopping condition.

I haven't done any prolog in a long time, but something structured similar to that could work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜