什么是不变量?

发布于 2024-07-05 09:09:16 字数 78 浏览 5 评论 0原文

这个词似乎在很多情况下都有使用。 我能想到的最好的办法是,它们意味着一个无法改变的变量。 这不就是常量/决赛(该死的Java!)的用途吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

遮云壑 2024-07-12 09:09:16

这个答案是给我5岁的孩子的。 不要将不变量视为常数或固定数值。 但确实可以。 然而,事情还不止于此。

相反,不变量类似于不同实体之间的固定关系。 例如,与你的亲生父母相比,你的年龄永远小于你的年龄。 你的年龄和你父母的年龄都会随着时间的推移而改变,但我上面提到的关系是不变的。

不变量也可以是数值常数。 例如,pi 的值是圆的周长与其直径之间的不变比率。 无论圆有多大或多小,该比率始终是pi

This answer is for my 5 year old kid. Do not think of an invariant as a constant or fixed numerical value. But it can be. However, it is more than that.

Rather, an invariant is something like of a fixed relationship between varying entities. For example, your age will always be less than that compared to your biological parents. Both your age, and your parent's age changes in the passage of time, but the relationship that i mentioned above is an invariant.

An invariant can also be a numerical constant. For example, the value of pi is an invariant ratio between the circle's circumference over its diameter. No matter how big or small the circle is, that ratio will always be pi.

萌面超妹 2024-07-12 09:09:16

维基百科的魔力:不变(计算机科学)

在计算机科学中,一个谓词,
如果为真,则在整个过程中都将保持不变
具体的操作顺序是
称为(一个)不变的
序列。

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.

冷清清 2024-07-12 09:09:16

您知道该条件在逻辑中的特定位置始终为真,并且可以在调试时进行检查以找出问题所在。

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.

辞取 2024-07-12 09:09:16

不变量比变量更具“概念性”。 一般来说,它是程序状态的一个属性,始终为真。 确保不变量成立的函数或方法被称为维持不变量。

例如,二叉搜索树可能具有这样的不变性:对于每个节点,该节点的左子节点的键小于该节点自己的键。 为该树正确编写的插入函数将保持该不变性。

正如您所知,这不是可以存储在变量中的内容:它更像是关于程序的声明。 通过弄清楚你的程序应该维护什么样的不变量,然后检查你的代码以确保它确实维护了这些不变量,你可以避免代码中的逻辑错误。

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.

默嘫て 2024-07-12 09:09:16

我通常更多地从算法或结构的角度来看待它们。

例如,您可以有一个可以断言的循环不变量——在每次迭代的开始或结束时始终为 true。 也就是说,如果您的循环应该处理从一个堆栈到另一个堆栈的对象集合,您可以说 |stack1|+|stack2|=c,位于循环的顶部或底部。

如果不变检查失败,则表明出现了问题。 在此示例中,这可能意味着您忘记将已处理的元素推入最终堆栈等。

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.

从﹋此江山别 2024-07-12 09:09:16

正如这一行所说:

在计算机科学中,如果谓词为真,则在整个特定的操作序列中将保持为真,称为该序列的不变性。

为了更好地理解这一点,希望这个 C++ 示例有所帮助。

考虑这样一个场景,您必须获取一些值,并在名为 count 的变量中获取它们的总数,并将它们添加到名为 sum 的变量中

。不变(同样,它更像是一个概念):

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

上面的代码将是这样的,

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

上面的代码做了什么?

1)从 cin 读取输入 并将它们放入 x

2) 成功读取一次后,递增 countsum = sum + x

3) 重复 1-2,直到读取停止(即 ctrl+D)

循环不变式:

不变式必须为 True ALWAYS。 开始您的代码

while(cin>>x){
  }

因此,最初您只使用此循环从标准输入读取数据并将数据存储在 x 中 。 好吧,很好。 但是不变量变得错误,因为我们的不变量的第一部分没有被遵循(或保持为真)。

// we have read count grades so far, and

如何保持不变量为真?

简单的! 增量计数。

所以 ++count; 会很好! 现在我们的代码变成了这样,

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

但是

即使现在我们的不变量(一个必须是TRUE的概念)也是False,因为现在我们不满足我们的不变量的第二部分。

// sum is the sum of the first count grades

那么现在该怎么办呢?

x 添加到 sum 中,并将其存储在 sum (sum+=x) 中,下次再使用
cin>>x 会将新值读取到 x 中。

现在我们的代码变成这样,

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

让我们​​检查

代码是否与我们的不变

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

代码匹配:

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

啊!。 现在,循环不变式始终为True,并且代码可以正常工作。

上面的示例是从 Andrew-koening 和 Barbara-E 所著的《Accelerated C++》一书中获取并修改的

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

总以为 2024-07-12 09:09:16

ADT 不变量指定关系
数据字段(实例变量)
在之前和之后都必须始终如此
任何实例方法的执行。

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.

淡淡绿茶香 2024-07-12 09:09:16

Java Concurrency in Practice 一书中有一个关于不变量及其重要性的出色示例。

虽然以 Java 为中心,但该示例描述了一些负责计算所提供整数的因子的代码。 示例代码尝试缓存最后提供的数字以及为提高性能而计算的因子。 在此场景中,示例代码中未考虑到一个不变量,这使得代码容易受到并发场景中竞争条件的影响。

输入图片此处描述

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.

enter image description here

dawn曙光 2024-07-12 09:09:16

类不变

类不变是一个条件,在调用相关函数之前和之后应该始终为真。

例如,平衡树有一个不变,称为<代码>isBalanced。 当您通过某些方法(例如 addNode、removeNode...)修改树时 - 在修改树之前和之后 isBalanced 应始终为 true

Class Invariant

Class Invariant is a condition which should be always true before and after calling relevant function

For example balanced tree has an Invariant which is called isBalanced. When you modify your tree through some methods (e.g. addNode, removeNode...) - isBalanced should be always true before and after modifying the tree

青春有你 2024-07-12 09:09:16

代码块内不会改变的东西

Something that doesn't change within a block of code

旧人 2024-07-12 09:09:16

这里的所有答案都很好,但我觉得我可以对这个问题有更多的了解:

从语言的角度来看,不变意味着永远不会改变的东西。 尽管这个概念实际上来自数学,但与归纳法相结合时,它是流行的证明技术之一。

证明是这样的,如果你能找到一个处于初始状态的不变量,并且无论对状态应用任何[合法]变换,这个不变量都持续存在,那么你可以证明如果某个状态不存在这个不变,那么无论对初始状态应用什么变换序列,它都永远不会发生。

现在,以前的思维方式(再次与归纳相结合)使得预测计算机软件的逻辑成为可能。 当执行进入循环时尤其重要,其中不变量可以用来证明某个循环将产生某个结果或者它永远不会以某种方式改变程序的状态。

当使用不变量来谓词循环逻辑时,其称为循环不变量。 它可以在循环之外使用,但是对于循环来说它确实很重要,因为你经常有很多可能性,或者无限多种可能性。

请注意,我使用“谓词”这个词来表示计算机软件的逻辑,而不是证明。 这是因为在数学中不变可以用作证明,但它永远不能证明计算机软件在执行时会产生预期的结果,由于软件是在许多抽象之上执行的,因此永远无法证明它们会产生预期的结果(例如,考虑硬件抽象)。

最后,从理论上严格预测软件逻辑仅对医疗和军事等高关键应用很重要。 不变式仍然可以用来帮助典型的程序员进行调试。 它可以用来知道程序在某个位置的哪个位置失败,因为它无法维持某个不变量——我们中的许多人无论如何都在使用它而不考虑它。

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.

野心澎湃 2024-07-12 09:09:16

从本质上讲,不变量在编写干净的代码时非常有用,因为从概念上知道代码中应该存在哪些不变量可以让您轻松决定如何组织代码以实现这些目标。 如前所述,它们在调试中也很有用,因为检查不变量是否得到维护通常是查看您尝试执行的任何操作是否真正按照您想要的方式进行的好方法。

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.

断爱 2024-07-12 09:09:16

它通常是在某些数学运算下不会改变的量。
示例是一个标量,在旋转下不会改变。 例如,在磁共振成像中,通过旋转不变量来表征组织特性是有用的,因为这样它的估计理想地不依赖于扫描仪中身体的方向。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文