I wrote this mini pseudo code that solves the equation using the Euler method:
// y'= x^2 - 5y
int n = 10; // count of steps
double h = 0.5; // step
double x = 0;
double y = 1;
for (int i = 0; i < n; i++) {
y += h * (x * x - 5 * y);
x += h;
}
write << y; //result
Now I am trying to write this in Prolog language
loop2(N,H,X,Y) :-
N > 0,
write(Y), nl,
Y is Y + H * (X * X - 5 * Y),
X is X + H,
S is N - 1,
loop2(S, H, X, Y).
Here I solved the example on a piece of paper and should get 62.5
But in Prolog my Output =
?- loop2(10, 0.5, 0, 1).
1
false.
>Solution :
X is X + H
becomes 0 is 0 + 0.5
and it is not, so case closed as far as Prolog is concerned, it has found your logical code is false
, and reports that to you. You did tell it to writeln(Y)
before that, so you still see 1
while it was trying.
You need to use new variable names for the results of calculations like you have used S is N - 1
, e.g. Xnext is X + H
.
The way you have shaped the countdown, S
will eventually become 0
and then N > 0
will be false and the whole thing will fail then. You can probably get away with using this to write
the values before it eventually fails, but a more normal way to end recursion is to have
loop2(0,_,_,_).
loop2(N,H,X,Y) :-
...
which says that when the call to loop2
happens, the top one is found first, if the first position is 0, then it succeeds. That ends the recursion and the whole thing succeeds.