2013-12-18 163 views
1

我需要一個Prolog中的謂詞,它產生如下進程:正在搜索一個Prolog謂詞

[0,0.1,0.2,0.3,...,defined end]。

我只知道內置間/ 3,但對你的幫助只產生整數像0,1,2,3 ......

謝謝!

回答

4

下面是一個還原(沒有錯誤檢查,它可能有一些精度誤差爲一些浮點數)之間:

between_step(First, Last, Step, Var) :- 
    NrSteps is integer((Last - First)/Step), 
    between(0, NrSteps, TempVar), 
    Var is First + Step * TempVar. 

一些有用的例子:

?- between_step(2.5, 3, 0.1, X). 
X = 2.5 ?; 
X = 2.6 ?; 
X = 2.7 ?; 
X = 2.8 ?; 
X = 2.9 ?; 
X = 3.0 

?- findall(X, between_step(0, 1, 0.1, X), Xs). 
Xs = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] 
yes 
+0

MH,如果我稱爲 「的findall(X,between_step(0,10,0.1,X)中,X)」 時,得到的解決方案:XS = [0.0,0.1,0.2,0.30000000000000004,0.4%,0.5 ,0.6000000000000001,0.7000000000000001,0.8 |。任何建議來解決它?! – mrbela

+0

你說的是0.30000000000000004而不是0.3嗎? –

+0

是的!對不起,我沒有提到它。 – mrbela

0

你可以嘗試一些像下面這樣,但如果你問我,通過回溯模仿程序循環的結構是Prolog code smell,表明你的設計與Prolog的工作方式有阻抗不匹配。

for(From,To,Step,From) :- % Unify the incremental value with the current 'From' 
    Step > 0 ,   % - when the 'Step' is positive, and 
    From =< To .   % - the 'To' limit has not been exceeded. 
for(From,To,Step,Inc) :- % On backtracking... 
    Step > 0   ,  % - when the 'Step' is positive, 
    From < To   ,  % - and the 'To' limit has not yet been reached 
    Next is From+Step ,  % - increment 'From' 
    for(Next,To,Step,Inc) . % - and recurse down. 
for(From,To,Step,From) :- % Unify the incremental value with the current 'From' 
    Step < 0 ,    % - when the 'Step' is negative, and 
    From >= To .   % - the 'To' limit has not been exceeded 
for(From,To,Step,Inc) :- % On backtracking... 
    Step < 0   ,  % - when the 'Step' is negative, and 
    From > To   ,  % - the 'To' limit has not yet been reached 
    Next is From+Step ,  % - decrement 'From' 
    for(Next,To,Step,Inc) . % - and recurse down