在prolog中将float转换为整数 [英] convert float to integer in prolog

查看:114
本文介绍了在prolog中将float转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在序言中将float转换为整数?

How to convert float to integer in prolog?

我尝试过:

?- integer(truncate(sqrt(9))).
false.

?- integer(round(sqrt(9))).
false.

推荐答案

您使用的谓词integer/1为true iff ,其参数为整数.由于术语truncate(sqrt(9))不是 整数,因此谓词 not 不成立,因此该术语失败.

The predicate integer/1 that you used is true iff its argument is an integer. Since the term truncate(sqrt(9)) is not an integer, the predicate does not hold and therefore fails for this term.

至少有两种方法可以获取想要的东西:

There are at least two ways to get what you want:

您可以使用谓词(is)/2在不同的数字表示形式之间进行转换.特别要检查算术功能 roundtruncateceiling.例如:

You can use the predicate (is)/2 for conversion between different number representations. In particular, check out the arithmetic functions round, truncate and ceiling. For example:


?- X is round(sqrt(9)).
X = 3.

但是,请注意,使用浮点数总是严重问题.例如:

However, note that using floating point numbers is always highly problematic. For example:


?- X is sqrt(2^10000).
ERROR: is/2: Arithmetic: evaluation error: `float_overflow'

还有其他一些问题,例如四舍五入错误和可能的下溢.

There are also other issues such as rounding errors and possible underflow.

由于浮点数的固有缺点,我强烈建议您改用更通用的机制.例如,一些Prolog系统支持有理数和具有无限精度的整数,而浮点数始终限于机器精度.

Due to the inherent shortcomings of floating point numbers, I strongly recommend you use more general mechanisms instead. For example several Prolog systems support rational numbers and integers with unbounded precision, whereas floats are always limited to machine precision.

如果您需要整数平方根,请使用例如有限域约束.在有约束的情况下,只要声明表示正平方根的整数X保持力即可:

If you need integer square roots, use for example finite domain constraints. With constraints, it suffices to state what holds for an integer X that denotes the positive square root:


?- X*X #= 9, X #>= 0.
X = 3.

适用于较大的整数:


?- X*X #= 2^10000, X #>= 0.
X = 1412467032...(1496 digits omitted)

有关更多信息,请参见的问题.

See clpfd for more information.

这篇关于在prolog中将float转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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