What is an invariant?

二次信任 提交于 2019-12-17 15:05:32

问题


The word seems to get used in a number of contexts. The best I can figure is that they mean a variable that can't change. Isn't that what constants/finals (darn you Java!) are for?


回答1:


An invariant is more "conceptual" than a variable. In general, it's a property of the program state that is always true. A function or method that ensures that the invariant holds is said to maintain the invariant.

For instance, a binary search tree might have the invariant that for every node, the key of the node's left child is less than the node's own key. A correctly written insertion function for this tree will maintain that invariant.

As you can tell, that's not the sort of thing you can store in a variable: it's more a statement about the program. By figuring out what sort of invariants your program should maintain, then reviewing your code to make sure that it actually maintains those invariants, you can avoid logical errors in your code.




回答2:


It is a condition you know to always be true at a particular place in your logic and can check for when debugging to work out what has gone wrong.




回答3:


I usually view them more in terms of algorithms or structures.

For example, you could have a loop invariant that could be asserted--always true at the beginning or end of each iteration. That is, if your loop was supposed to process a collection of objects from one stack to another, you could say that |stack1|+|stack2|=c, at the top or bottom of the loop.

If the invariant check failed, it would indicate something went wrong. In this example, it could mean that you forgot to push the processed element onto the final stack, etc.




回答4:


The magic of wikipedia: Invariant (computer science)

In computer science, a predicate that, if true, will remain true throughout a specific sequence of operations, is called (an) invariant to that sequence.




回答5:


As this line states:

In computer science, a predicate that, if true, will remain true throughout a specific sequence of operations, is called (an) invariant to that sequence.

To better understand this hope this example in C++ helps.

Consider a scenario where you have to get some values and get the total count of them in a variable called as count and add them in a variable called as sum

The invariant (again it's more like a concept):

// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades

The code for the above would be something like this,

int count=0;
double sum=0,x=0;
while (cin >> x) {
++count;
sum+=x;
}

What the above code does?

1) Reads the input from cin and puts them in x

2) After one successful read, increment count and sum = sum + x

3) Repeat 1-2 until read stops ( i.e ctrl+D)

Loop invariant:

The invariant must be True ALWAYS. So initially you start out your code with just this

while(cin>>x){
  }

This loop reads data from standard input and stores in x. Well and good. But the invariant becomes false because the first part of our invariant wasn't followed (or kept true).

// we have read count grades so far, and

How to keep the invariant true?

Simple! increment count.

So ++count; would do good!. Now our code becomes something like this,

while(cin>>x){
 ++count; 
 }

But

Even now our invariant (a concept which must be TRUE) is False because now we didn't satisfy the second part of our invariant.

// sum is the sum of the first count grades

So what to do now?

Add x to sum and store it in sum ( sum+=x) and the next time cin>>x will read a new value into x.

Now our code becomes something like this,

while(cin>>x){
 ++count; 
 sum+=x;
 }

Let's check

Whether code matches our invariant

// invariant:
// we have read count grades so far, and
// sum is the sum of the first count grades

code:

while(cin>>x){
 ++count; 
 sum+=x;
 }

Ah!. Now the loop invariant is True always and code works fine.

The above example was taken and modified from the book Accelerated C++ by Andrew-koening and Barbara-E




回答6:


Something that doesn't change within a block of code




回答7:


Following on from what it is, invariants are quite useful in writing clean code, since knowing conceptually what invariants should be present in your code allows you to easily decide how to organize your code to reach those aims. As mentioned ealier, they're also useful in debugging, as checking to see if the invariant's being maintained is often a good way of seeing if whatever manipulation you're attempting to perform is actually doing what you want it to.




回答8:


It's typically a quantity that does not change under certain mathematical operations. An example is a scalar, which does not change under rotations. In magnetic resonance imaging, for example, it is useful to characterize a tissue property by a rotational invariant, because then its estimation ideally does not depend on the orientation of the body in the scanner.




回答9:


The ADT invariant specifes relationships among the data fields (instance variables) that must always be true before and after the execution of any instance method.




回答10:


There is an excellent example of an invariant and why it matters in the book Java Concurrency in Practice.

Although Java-centric, the example describes some code that is responsible for calculating the factors of a provided integer. The example code attempts to cache the last number provided, and the factors that were calculated to improve performance. In this scenario there is an invariant that was not accounted for in the example code which has left the code susceptible to race conditions in a concurrent scenario.




回答11:


All the answers here are great, but i felt that i can shed more light on the matter:

Invariant from a language point of view means something that never changes. The concept though comes actually from math, it's one of the popular proof techniques when combined with induction.

Here is how a proof goes, If you can find an invariant that is in the initial state, And that this invariant persists regardless of any [legal] transformation applied to the state, then you can prove that If a certain state does not have this invariant then it can never occur, no matter what sequence of transformations are applied to the initial state.

Now the previous way of thinking (again combined with induction) makes it possible to predicate the logic of computer software. Especially important when the execution goes in loops, in which an invariant can be used to prove that a certain loop will yield a certain result or that it will never change the state of a program in a certain way.

When invariant is used to predicate a loop logic its called loop invariant. It can be used outside loops, but for loops it is really important, because you often have a lot of possibilities, or an infinite number of possibilities.

Notice that i use the word "predicate" the logic of a computer software, and not prove. And that's because while in math invariant can be used as a proof, it can never prove that the computer software when executed will yield what is expected, due to the fact that the software is executed on top of many abstractions, that can never be proved that they will yield what is expected (think of the hardware abstraction for example).

Finally while theoretically and rigorously predicting software logic is only important for high critical applications like Medical, and Military ones. Invariant can still be used to aid the typical programmer when debugging. It can be used to know where at a certain location The program failed because it has failed to maintain a certain invariant - many of us use it anyway without giving a thought about it.



来源:https://stackoverflow.com/questions/112064/what-is-an-invariant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!