什么是不变式? [英] What is an invariant?

查看:480
本文介绍了什么是不变式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个词似乎在许多上下文中都得到了使用.我能想到的最好的是,它们表示一个不变的变量.这不是常量/最终用途(对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?

推荐答案

不变量比变量更概念上".通常,它是程序状态的始终为真的属性.可以确保保持不变的函数或方法称为保持不变.

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.

这篇关于什么是不变式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆