mirror of
https://github.com/Z3Prover/z3
synced 2025-04-12 04:03:39 +00:00
Add support for Python Fraction object
Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
parent
d0d48c7ce2
commit
a51c6d125d
|
@ -44,6 +44,7 @@ from z3core import *
|
||||||
from z3types import *
|
from z3types import *
|
||||||
from z3consts import *
|
from z3consts import *
|
||||||
from z3printer import *
|
from z3printer import *
|
||||||
|
from fractions import Fraction
|
||||||
import sys
|
import sys
|
||||||
import io
|
import io
|
||||||
|
|
||||||
|
@ -2523,6 +2524,15 @@ class RatNumRef(ArithRef):
|
||||||
"""
|
"""
|
||||||
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
|
return Z3_get_numeral_string(self.ctx_ref(), self.as_ast())
|
||||||
|
|
||||||
|
def as_fraction(self):
|
||||||
|
"""Return a Z3 rational as a Python Fraction object.
|
||||||
|
|
||||||
|
>>> v = RealVal("1/5")
|
||||||
|
>>> v.as_fraction()
|
||||||
|
Fraction(1, 5)
|
||||||
|
"""
|
||||||
|
return Fraction(self.numerator_as_long(), self.denominator_as_long())
|
||||||
|
|
||||||
class AlgebraicNumRef(ArithRef):
|
class AlgebraicNumRef(ArithRef):
|
||||||
"""Algebraic irrational values."""
|
"""Algebraic irrational values."""
|
||||||
|
|
||||||
|
|
|
@ -8,6 +8,7 @@
|
||||||
from z3 import *
|
from z3 import *
|
||||||
from z3core import *
|
from z3core import *
|
||||||
from z3printer import *
|
from z3printer import *
|
||||||
|
from fractions import Fraction
|
||||||
|
|
||||||
def _to_numeral(num, ctx=None):
|
def _to_numeral(num, ctx=None):
|
||||||
if isinstance(num, Numeral):
|
if isinstance(num, Numeral):
|
||||||
|
@ -170,6 +171,14 @@ class Numeral:
|
||||||
assert(self.is_integer())
|
assert(self.is_integer())
|
||||||
return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast()))
|
return long(Z3_get_numeral_string(self.ctx_ref(), self.as_ast()))
|
||||||
|
|
||||||
|
def as_fraction(self):
|
||||||
|
""" Return a numeral (that is a rational) as a Python Fraction.
|
||||||
|
>>> Numeral("1/5").as_fraction()
|
||||||
|
Fraction(1, 5)
|
||||||
|
"""
|
||||||
|
assert(self.is_rational())
|
||||||
|
return Fraction(self.numerator().as_long(), self.denominator().as_long())
|
||||||
|
|
||||||
def approx(self, precision=10):
|
def approx(self, precision=10):
|
||||||
"""Return a numeral that approximates the numeral `self`.
|
"""Return a numeral that approximates the numeral `self`.
|
||||||
The result `r` is such that |r - self| <= 1/10^precision
|
The result `r` is such that |r - self| <= 1/10^precision
|
||||||
|
|
Loading…
Reference in a new issue