将 Z3 Real 转换为浮动

Casting Z3 Real into float

有没有办法将 Real 值转换为浮点数,以便 python 可以在 z3 完成后使用这些值?

x = RealVal("1/3")
print(x.sort())
print(float(x))

请注意,您不能将 z3 实数值转换为浮点数。 z3 实数值是无限精确的实数,不能忠实地表示为具有固有精度限制的浮点值。

相反,您想将其转换为 Python 分数:https://www.tutorialspoint.com/fraction-module-in-python 它可以表示所有 z3 实数值,只要它们不是多项式的无理根。 (你可以忽略最后的评论,除非你在 z3 中使用完整的代数实数。)

为此,请使用 as_fraction 方法:

from z3 import *

x = RealVal("1/3")
x2 = x.as_fraction()
print type(x2)
print x2

这会打印:

<class 'fractions.Fraction'>
1/3

如果你真的想要,你可以把它变成一个浮点数:

x_float = float(x2.numerator) / float(x2.denominator)
print type(x_float)
print x_float

这会打印:

<type 'float'>
0.333333333333

但显然你现在已经失去了精度。