I started learning Dafny and I just learned invariants. I've got this code:
function pot(m:int, n:nat): int
{
if n==0 then 1
else if n==1 then m
else if m==0 then 0
else pot(m,n-1) * m
}
method Pot(m:int, n:nat) returns (x:int)
ensures x == pot(m,n)
{
x:=1;
var i:=0;
if n==0 {x:=1;}
while i<=n
invariant i<=n;
{
x:=m*x;
i:=i+1;
}
}
And the given error is the following: "This loop invariant might not be maintained by the loop." I think I might need another invariant, but I think my code is correct other than that (I guess). Any help is appreciated. Thanks in advance.
A loop invariant must hold whenever the loop branch condition is evaluated. But on the last iteration of your loop, i will actually be n+1, so the loop invariant is not true then.
Changing the loop invariant to i <= n + 1 or changing the loop branch condition to i < n will fix this particular problem.
After that, you will still have some work to do to finish proving the method correct. Feel free to ask further questions if you get stuck.
Related
I was doing exercise about program verification, and I had some difficulties in finding this loop invariant:
y = 0;
while (y != x) {
y = y + 1;
}
the
precondition is x>=0 and the postcondition is x=y
In the loop there is just one variable so I couldn't think any possible relation that is preserved throughout the program. One weak invariant so far is (y>= 0 && y<=x). So what is the suitable loop invariant for this program?
Let me give you a hint: loop invariants must be expressed in terms of each iteration i. That is, it must be something like "P is true before the execution of every iteration i". The invariant you've come up with is not expressed as a function of i. Try modifying it a little bit and I think you'll find a more suitable loop invariant.
If you get stuck, I recommend you check out the book title "Discrete Mathematics with Applications", by Susanna Epp; it has a chapter on loop invariants and the book is very gentle for beginners.
This is a very basic question but please bear with me!
I got this code in a question as part of a quiz I was doing earlier and just didn't know if I might be missing something. I typed it into the editor and it would not run and it does appear to be incomplete. Had it been if (k) it would have made more sense.
But, as I have heard that you can leave out components of a for loop, I was just wondering if there is any time you would see the likes of for (k)?
int k = 0;
for (k) {
printf ("hello");
}
for(int k; ;)
/*this is the correct syntax of a for loop without conditional statement and incrementation/decrementation statement*\
Remember,those semi-colons within the paranthesis is important(without that the program wouldn't compile).
Now,to answer some of the questions you asked me in the earlier answer-
for(int k; ;)
{
printf("infinite loop");
}
When will this loop come to an end?
This loop will never come to an end.It is an infinite loop.It will keep printing infinite loop forever.
Is it possible to bring this loop to an end?
Yes,it is.It can be brought to an end using break statement.
for(int k; ;)
//or for( ; ; )
{
printf("infinite loop");
break;
}
Prints infinte loop only once.It will encounter the break statement and the control will move outside the loop.
Possible application.
It's used when you actually have no idea about when a loop should come to an end.
int i=0; //to take user input
for(int k; ;)
{
//accept the value of k from user.
/*You want the user to enter 1 as the input*/
if(k==1)
{
printf("entered 1,moving out of loop");
break;
}
}
What is the meaning of above loop?
- This loop keeps running until the user enters '1'.This is important in cases where you are giving the user options and the options are limited and so you don't want the user to give an invalid input.It runs until a valid input is entered(you can add more if statements with break statement).
Menu: 1)Pizza
2)Burger
3)Quit buying!
for(int k;k<10;k++)
/* this is a finite loop and this isn't suitable for the above requirement because you are not sure if the user will give the valid input within 10 iterations.*/
When k becomes 10,the control will move out irrespective of whether the user has entered a valid input or not.What if the user inputs 8 when k=9? The control will move out of the loop at k=10.As a result,your program will not work efficiently because i=8 is not an input you expected.You wanted 1,2 or 3 as input.
So,an infinite loop is used when you are not sure about how many iterations are required.You will actually be using a break statement to exit such a loop.
Is this the only option for an infinite loop?Why not while() ?Isn't while() with no condition an infinite loop?
while();// invalid in C.
//objective-C follows C-standards.
while("condition"); //valid
Some valid for loop declarations in C
for(k; ;) // infinite loop
for(; ;) // infinite loop
for(; k<0;)// valid
So,I think that sums up a small explanation.
Remember,semi-colons are important(irrespective of whether a condition is given or not).
And of course,you have other options to keep running or taking user input unless a valid input is given.But above one was just an application I could figure out to show that an infinite loop could be cool!
If you find any error or doubt,please comment.
Well,even I am not too good in C.But yeah since java is somewhat similar,I figured it out.
I'm interest in building an SVM multi class classifier, so I am currently implementing
Sequential minimal optimization SMO.
My implementation is based on the pseudo code in
`Fast Training of Support Vector Machines using Sequential Minimal Optimization" by John C. Platt
I observed that for certain training examples. The Smo may diverge and run into an infinite loop
The following loop in the main routine
numChanged = 0;
examineAll = 1;
while (numChanged > 0 || examineAll >0) {…}
may run into an infinite loop.
Is there there clue or criterion to prevent the smo algorithm routine from running into an infinite loop?
I would like to thank you for your answer.
Regards
You can add a max iteration condition if you want:
while ((numChanged > 0 || examineAll) && iter < MaxIter)
but for most cases it shouldn't run into an infinite loop, this is the full Platt's pseudocode:
while (numChanged > 0 || examineAll)
{
numChanged = 0;
// Adding curly brackets for better readability
if (examineAll)
{
loop I over all training examples
numChanged += examineExample(I);
}
else
{
loop I over examples where alpha is not 0 & not C
numChanged += examineExample(I);
}
if (examineAll == 1)
{
examineAll = 0;
}
else
{
examineAll = 1;
}
}
Notice that what it is doing is performing an iteration to examine the example and the next one do the same just to those examples where alpha is not 0 or C. If nothing changes after the "examine all" iteration, the while loop condition will be false hence stopping the loop.
So, for that to be in a infinite loop there must be a corner case (probably a numerical error) that introduce oscillations making examples to change during the examine all phase but not changing in the "examine only alpha == 0 and C".
Usually if the data is normalized in [-1,1] or [0,1] and the parameters of the algorithm have reasonable values, those corner cases would be rare. In any case, if you want to be extra careful you can put the max-iter safety net.
I have a simple question with regards to initializing for loops.
Here is my for loop declaration:
for (int i=player.x-xIndex-1; i<=player.x+xIndex+1; i++)
{
for (int j=player.y-yIndex-1; j<=player.y+yIndex+1; j++)
{
}
}
My question is:
Is it bad practice to have the values of the indices i and j be set to non-static integer values at declaration?
Will the code just evaluate the minimum and maximum values of i and j once at beginning of execution, or will it evaluate those values (i.e. player.x+xIndex+1, etc.) every single time the loop executes.
Any light you guys can shed on my problem would be awesome!
I'm a freakin' amateur, guys. Seriously.
Thanks :D
Not an amateur question at all. The "initialization" expressions are calculated only on the first run through, because of course they're only used that one time.
For the loop's "condition" (the middle expression that is tested at the end of every iteration), in the worst case it can be evaluated every iteration. Because what if (in this case) player.y actually changes during the loop?
However, most modern compilers will likely not compute that whole thing every loop if they can detect that the end value is provably never changing during the loop.
If you wanted to be double sure and manhandle the path of execution, you can explicitly "hoist" the conditional end expression out of the loop yourself, like:
int maxValue = foo.x + y.bar + 12 + myString.length;
for (int i = 0; i < maxValue; i++) {
....
But now the standard style disclaimer: optimizing prematurely can make your code less readable for no provable gains. Unless you're doing real work in that condition expression, or the loop is running bazillions of iterations, some additional computation won't hurt you much, and might be worth keeping so that it's clearer to yourself and others what you're trying to do.
I am writing a battleship program. Right now I am testing a couple lines of code to see if it will place the boat going in the up direction. How my program is set up is that if, for example, the user clicks on the aircraft carrier button to set his aircraft carrier, the program should also set the ai's aircraft carrier. The boats are placed on a button array, called tlba. aifirstclicki is set by a random generator so that it will choose a random row. aifirstclickj chooses a random column, in conjunction the two pinpoint a spot on the button array (which is 10x10). I wrote the following code to try to make it so that if the program has an outofboundsexception error,or in other words if the program chooses a first spot that will eventually cause an outofbounds exception error because the for loop will keep adding spots until aiclickcount = 5, it should start over and pick a different spot until it finds a spot that will allow it to place all 5 spots. I keep getting stuck in an infinite loop though.
int aiclickcount = 0;
while (directiondecider == 0)
{//up
aifirstclicki = generator.nextInt(10);
aifirstclickj = generator.nextInt(10);
while (aifirstclicki != 3 &&
aifirstclicki != 2 &&
aifirstclicki != 1 &&
aifirstclicki != 0)
{
for(int k=0; k<shiplength; k++)
{
tlba[aifirstclicki - k][aifirstclickj].setBackground(Color.RED);
aistringarray[aifirstclicki - k][aifirstclickj] = "aircraftcarrier";
aioccupied2d[aifirstclicki - k][aifirstclickj] = true;
aiclickcount++;
}
if (aiclickcount == 5)
{
shipset = true;
break;
}
}
System.out.println(shipset);
}
Does anyone know what's wrong or have a different solution to my problem?
You never have aiclickcount == 5 if your shiplength is not 5. Put if into your for loop. You don't need the second while at all, you don't break out of it as well. Just generate number greater than 3 by nextInt(6) + 4.
Your code does not tell us, which value the variable shiplength has. If it's 0 the for-loop will never be entered thus aiclickcount will remain 0 and your break statement is never reached (under the premise that the random value of aifirstclicki is greater than 3).
Try to step through your code with a debugger and let it display the values for the variables to you to find out what's going on.
Your break; is only going to get you out of the second while loop, not the first as it only works on the inner-most loop that it is part of.
Java allows you to specify multi-level breaks, rather than having to complicate your loop conditions:
Breaking out of nested loops in Java