def RIFtol(*args): """ Create an element of the real interval field used for doctest tolerances. It allows large numbers like 1e1000, it parses strings with spaces like ``RIF(" - 1 ")`` out of the box and it carries a lot of precision. The latter is useful for testing libraries using arbitrary precision but not guaranteed rounding such as PARI. We use 1044 bits of precision, which should be good to deal with tolerances on numbers computed with 1024 bits of precision. The interval approach also means that we do not need to worry about rounding errors and it is also very natural to see a number with tolerance as an interval. EXAMPLES:: sage: from sage.doctest.parsing import RIFtol sage: RIFtol(-1, 1) 0.? sage: RIFtol(" - 1 ") -1 sage: RIFtol("1e1000") 1.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000?e1000 """ global _RIFtol if _RIFtol is None: # We need to import from sage.all to avoid circular imports. from sage.all import RealIntervalField _RIFtol = RealIntervalField(1044) return _RIFtol(*args)
def __init__(self, approx_hyperbolic_structure, bits_prec=53): if not (approx_hyperbolic_structure.exact_edges and approx_hyperbolic_structure.var_edges): raise Exception( "Did not pick exact/var edges: " "call HyperbolicStructure.pick_exact_and_var_edges.") self.mcomplex = approx_hyperbolic_structure.mcomplex self.exact_edges = approx_hyperbolic_structure.exact_edges self.var_edges = approx_hyperbolic_structure.var_edges self.bits_prec = bits_prec self.RIF = RealIntervalField(bits_prec) self.twoPi = self.RIF(2 * pi) self.initial_edge_lengths = vector( [self.RIF(e) for e in approx_hyperbolic_structure.edge_lengths]) self.approx_inverse = (approx_hyperbolic_structure. full_rank_jacobian_submatrix().change_ring( RealDoubleField()).inverse().change_ring( self.RIF)) self.identity = matrix.identity(self.RIF, len(self.var_edges)) self.certified_edge_lengths = None
def setup_fields_and_triangles(self): from sage.all import RealIntervalField, ComplexIntervalField, sin, cos, exp self.RIF = RealIntervalField(120) self.CIF = ComplexIntervalField(120) alpha = self.RIF(0.4) self.finiteTriangle1 = FiniteTriangle([ FinitePoint(z=exp(self.CIF(0, 2.1 * i + 0.1)) * cos(alpha), t=sin(alpha)) for i in range(3) ]) self.idealTriangle1 = IdealTriangle([ ProjectivePoint(z=exp(self.CIF(0, 2.1 * i + 0.1))) for i in range(3) ]) self.idealTriangle2 = IdealTriangle( [ProjectivePoint(self.CIF(z)) for z in [-1, 0, 1]]) self.idealTriangle3 = IdealTriangle([ ProjectivePoint(self.CIF(1)), ProjectivePoint(self.CIF(-1)), ProjectivePoint(self.CIF(0), True) ])
def __init__(self, tiling_engine, bits_prec=53): self.RIF = RealIntervalField(bits_prec) self.CIF = ComplexIntervalField(bits_prec) self.baseTetInCenter = FinitePoint( self.CIF(tiling_engine.baseTetInCenter.z), self.RIF(tiling_engine.baseTetInCenter.t)) self.generator_matrices = { g: m.change_ring(self.CIF) for g, m in tiling_engine.mcomplex.GeneratorMatrices.items() } self.max_values = {} for tile in tiling_engine.all_tiles(): if tile.word: matrix = prod(self.generator_matrices[g] for g in tile.word) tileCenter = FinitePoint(self.CIF(tile.center.z), self.RIF(tile.center.t)) err = tileCenter.dist( self.baseTetInCenter.translate_PSL(matrix)).upper() l = len(tile.word) self.max_values[l] = max(err, self.max_values.get(l, err))
def __init__(self, tiling_engine, bits_prec=2 * 53): self.RIF = RealIntervalField(bits_prec) self.CIF = ComplexIntervalField(bits_prec) self.baseTetInCenter = vector( self.RIF, complex_and_height_to_R13_time_vector( tiling_engine.baseTetInCenter.z, tiling_engine.baseTetInCenter.t)) self.generator_matrices = { g: matrix(self.RIF, PSL2C_to_O13(m)) for g, m in tiling_engine.mcomplex.GeneratorMatrices.items() } self.max_values = {} for tile in tiling_engine.all_tiles(): if tile.word: m = prod(self.generator_matrices[g] for g in tile.word) tileCenter = vector( self.RIF, complex_and_height_to_R13_time_vector( tile.center.z, tile.center.t)) #print("=====") #print(tileCenter) #print(m * self.baseTetInCenter) #print(inner_prod(m * self.baseTetInCenter, tileCenter).endpoints()) err = my_dist(m * self.baseTetInCenter, tileCenter).upper() l = len(tile.word) self.max_values[l] = max(err, self.max_values.get(l, err))
def get_tiling_engine(M, cut_off, bits_prec = 53): is_hyp, shapes = M.verify_hyperbolicity(bits_prec = bits_prec) if not is_hyp: raise ValueError("Manifold does not seem to be hyperbolic.") RIF = RealIntervalField(bits_prec) t = SpineTilingEngine.from_manifold_and_shapes(M, shapes, RIF(cut_off)) t.finish_tiling() return t
def has_value(v, values): RIF = RealIntervalField(212) for value in values: if abs(RIF(v.imag()) - RIF(value.imag())) < 1e-20: r = (RIF(v.real()) - RIF(value.real())) / RIF(pi**2 / 2) is_int, k = r.is_int() if is_int: if abs(r - k) < 1e-20: return True return False
def getone(n=None, digits=None, plain=False): if n is None: n = request.args.get('n', 0, int) if digits is None: digits = request.args.get('digits', 50, int) db = sqlite3.connect(dbpath) c = db.cursor() query = 'SELECT error_mantissa, error_exponent, mantissa, exponent ' +\ 'FROM stieltjes WHERE n = ? LIMIT 1' c.execute(query, (n, )) em, ee, mantissa, exponent = c.fetchone() mantissa = ZZ(mantissa) e = min(ee, exponent) em = em << (ee - e) mantissa = mantissa << (exponent - e) if digits is None: prec = RR(mantissa).log2() + 3 else: prec = digits * 3.3219280948873626 + 3 prec = max(2, prec) prec = min(prec, 200000) RIF = RealIntervalField(prec) x = RIF(mantissa - em, mantissa + em) if e < 0: x = x >> (-e) else: x = x << e if plain: return str(x) else: g, e = str(x).split('?') if e == '': g += '?' else: g += '? × 10<sup style="font-size:60%;">' + e[1:] + '</sup>' return render_template( 'getone.html', n=n, digits=digits, gamma=g, title=r"Stieltjes Constant $\gamma_{{{}}}$".format(n), bread=[ ('Stieltjes Constants', url_for('.stieltjes_constants')), (r'$\gamma_{{{}}}$'.format(n), ' '), ])
def matrices(self): from sage.all import RealIntervalField, ComplexIntervalField, matrix RIF = RealIntervalField(120) CIF = ComplexIntervalField(120) return [ matrix([[CIF(RIF(1.3), RIF(-0.4)), CIF(RIF(5.6), RIF(2.3))], [CIF(RIF(-0.3), RIF(0.1)), CIF(1)]]), matrix([[CIF(RIF(0.3), RIF(-1.4)), CIF(RIF(3.6), RIF(6.3))], [CIF(RIF(-0.3), RIF(1.1)), CIF(1)]]), matrix([[CIF(2.3, 1.2), CIF(0)], [CIF(0), CIF(1)]]), matrix([[CIF(2.3, 1.2), CIF(5)], [CIF(0), CIF(1)]]), matrix([[CIF(2.3, 1.2), CIF(0)], [CIF(5.6), CIF(1)]]), matrix([[CIF(1), CIF(10.0)], [CIF(0), CIF(1)]]), matrix([[CIF(1), CIF(0)], [CIF(10.0), CIF(1)]]), matrix([[CIF(0), CIF(-1)], [CIF(1), CIF(2)]]), matrix([[CIF(2), CIF(-1)], [CIF(1), CIF(0)]]) ]
def test_plane_point(self): from sage.all import RealIntervalField, ComplexIntervalField CIF = ComplexIntervalField(120) RIF = RealIntervalField(120) pts = [ ProjectivePoint(CIF(1.01)), ProjectivePoint(CIF(3)), ProjectivePoint(CIF(2, 1)) ] pt = FinitePoint(CIF(2, 5), RIF(3)) plane = PlaneReflection.from_three_projective_points(*pts) p = PlanePointDistanceEngine(plane, PointReflection.from_finite_point(pt)) e = p.endpoint() if not abs(p.dist() - pt.dist(e)) < 1e-20: raise Exception("Distance incorrect %r %r" % (p.dist(), pt.dist(e)))
def test_plane_plane(self): from sage.all import RealIntervalField, ComplexIntervalField CIF = ComplexIntervalField(120) RIF = RealIntervalField(120) pts = [[ ProjectivePoint(CIF(1)), ProjectivePoint(CIF(3)), ProjectivePoint(CIF(2, 1)) ], [ ProjectivePoint(CIF(-1)), ProjectivePoint(CIF(-3)), ProjectivePoint(CIF(-2, 1)) ]] planes = [ PlaneReflection.from_three_projective_points(*pt) for pt in pts ] p = PlanePlaneDistanceEngine(*planes) e = p.endpoints() if not abs(p.dist() - e[0].dist(e[1])) < 1e-20: raise Exception("Distance incorrect %r %r" % (p.dist(), e[0].dist(e[1]))) e_baseline = [ FinitePoint(CIF(1.5), RIF(0.75).sqrt()), FinitePoint(CIF(-1.5), RIF(0.75).sqrt()) ] for e0, e_baseline0 in zip(e, e_baseline): if not e0.dist(e_baseline0) < 1e-15: raise Exception("%s %s" % (e0, e_baseline0))
\ *(((\.){4}:)|((\.){3}))?\ *""") # Use this real interval field for doctest tolerances. It allows large # numbers like 1e1000, it parses strings with spaces like RIF(" - 1 ") # out of the box and it carries a lot of precision. The latter is # useful for testing libraries using arbitrary precision but not # guaranteed rounding such as PARI. We use 1044 bits of precision, # which should be good to deal with tolerances on numbers computed with # 1024 bits of precision. # # The interval approach also means that we do not need to worry about # rounding errors and it is also very natural to see a number with # tolerance as an interval. # We need to import from sage.all to avoid circular imports. from sage.all import RealIntervalField RIFtol = RealIntervalField(1044) # This is the correct pattern to match ISO/IEC 6429 ANSI escape sequences: # ansi_escape_sequence = re.compile( r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~]|\x9b.*?[@-~])') def remove_unicode_u(string): """ Given a string, try to remove all unicode u prefixes inside. This will help to keep the same doctest results in Python2 and Python3. The input string is typically the documentation of a method or function. This string may contain some letters u that are unicode python2 prefixes. The aim is to remove all of these u and only them.
random_marker = re.compile('.*random', re.I) tolerance_pattern = re.compile( r'\b((?:abs(?:olute)?)|(?:rel(?:ative)?))? *?tol(?:erance)?\b( +[0-9.e+-]+)?' ) backslash_replacer = re.compile(r"""(\s*)sage:(.*)\\\ * \ *(((\.){4}:)|((\.){3}))?\ *""") # Use this real interval field for doctest tolerances. It allows large # numbers like 1e1000, it parses strings with spaces like RIF(" - 1 ") # out of the box and it is slightly more precise than Python's 53 bits. # The interval approach also means that we do not need to worry about # rounding errors and it is also very natural to see a number with # tolerance as an interval. # We need to import from sage.all to avoid circular imports. from sage.all import RealIntervalField RIFtol = RealIntervalField(64) # This is the correct pattern to match ISO/IEC 6429 ANSI escape sequences: # #ansi_escape_sequence = re.compile(r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~]|\x9b.*?[@-~])') # # Unfortunately, we cannot use this, since the \x9b might be part of # a UTF-8 character. Once we have a unicode-aware doctest framework, we # should use the correct pattern including \x9b. For now, we use this # form without \x9b: ansi_escape_sequence = re.compile(r'(\x1b[@-Z\\-~]|\x1b\[.*?[@-~])') def parse_optional_tags(string): """ Returns a set consisting of the optional tags from the following
class lfunction_element: projection = [ 'Lhash', 'conductor', 'degree', 'id', 'index', 'label', 'order_of_vanishing', 'prelabel', 'primitive', 'root_angle', 'trace_hash', 'positive_zeros', 'positive_zeros_mid', 'positive_zeros_rad', ] def __init__(self, data, from_db=False): self.algebraic = True self.coeff_info = None self.dirichlet_coefficients = None # we prefer ai and euler_factors self.credit = None self.group = None self.st_group = None # we don't have the infrastructure to determine this on the fly self.symmetry_type = None self.sign_arg = None self.from_db = from_db if from_db: assert set(self.projection).issubset(set(data)) # convert from literal to integer data['conductor'] = int(data['conductor']) for i in range(2, 11): self.__dict__['A' + str(i)] = None self.__dict__.update(data) if hasattr(self, 'leading_term_arb'): self.leading_term_mid, self.leading_term_rad = realball_to_mid_rad_str(self.leading_term_arb) self.leading_term = None if hasattr(self, 'root_number_acb'): % 0.5 # sets # - root_angle: float # - sign_arg_mid: numeric # - sign_arg_rad: real # - root_number_mid: numeric[] # - root_number_rad: numeric[] self.root_number = None self.sign_arg = None if self.self_dual: # pindown root_number and its argument assert self.root_number_acb.contains_integer() root_number = Integer(self.root_number_acb) # pin it down self.root_number_acb = self.root_number_acb.parent()(root_number) arg = self.root_number_acb.real().parent()(0 if root_number == 1 else 0.5) else: arg = normalized_arg(self.root_number_acb) self.root_number_mid, self.root_number_rad = complexball_to_mid_rad_str(self.root_number_acb) self.sign_arg_mid, self.sign_arg_rad = realball_to_mid_rad_str(arg) self.root_angle = float(arg) if hasattr(self, 'special_values_acb'): if self.dual: # pin down the values to the real axis for elt in self.special_values_acb: assert elt.imag().contains_zero() self.special_values_acb = [elt.parent()(elt.real()) for elt in self.special_values_acb] sv = [(i + self.analytic_normalization, complexball_to_mid_rad_str(elt)) for (i, elt) in enumerate(self.special_values_acb, 1) if enough_digits(elt)] # at the moment artin and smalljac compute at the same points self.special_values_at = '{%s}' % ','.join(str(elt[0])for etl in sv) self.special_values_mid = '{%s}' % ','.join(elt[1][0] for elt in sv) self.special_values_rad = '{%s}' % ','.join(elt[1][1] for elt in sv) self.values = None if hasattr(self, 'positive_zeros_arb'): self.accuracy = self.precision = None # we are using balls # we increase the radius to 2**-103 => 31 digits max_rad = 2**-103 # doesn't change the radius if we pass a negative value z = [realball_to_mid_rad_str(elt.add_error(max_rad - elt.rad())) for elt in self.positive_zeros_arb] self.positive_zeros_mid = '{%s}' % ','.join([elt[0] for elt in z]) self.positive_zeros_rad = '{%s}' % ','.join([elt[1] for elt in z]) R = RealIntervalField(self.positive_zeros_arb[0].mid().prec()) # remove the question mark and the unknown digit self.z1 = str(R(self.positive_zeros_arb[0]))[:-2] self.z2 = str(R(self.positive_zeros_arb[1]))[:-2] self.z3 = str(R(self.positive_zeros_arb[2]))[:-2] if from_db: # we will use zero balls for comparisons to figure out label and/or factors if getattr(self, 'positive_zeros_rad', None) and getattr(self, 'positive_zeros_mid', None): R = RealBallField(self.positive_zeros_mid[0].prec()) self.positive_zeros_arb = [R(m, r) for m, r in zip(self.positive_zeros_mid, self.positive_zeros_rad)] elif getattr(self, 'positive_zeros', None): if getattr(self, 'accuracy', None) == 100: z1int = self.Lhash.split(',')[0] self.positive_zeros_arb = [ball_from_midpoint(z) for z in self.positive_zeros] assert self.Lhash.split(',')[0] == mid_point_100bits(self.positive_zeros_arb[0]) else: self.positive_zeros_arb = [numeric_to_ball(z) for z in self.positive_zeros] else: assert False, '%s' % data
def arg_hack(foo): if not foo.real().contains_zero() and foo.real().mid() < 0: arg = (-foo).arg() #print arg if arg > 0: arg -= foo.parent().pi().real() else: arg += foo.parent().pi().real() return arg else: return foo.arg() # other globals CCC = ComplexBallField(2000) RRR = RealIntervalField(2000) def CBFlistcmp(L1, L2): for (z1, z2) in zip(L1, L2): x1, y1 = z1.real(), z1.imag() x2, y2 = z2.real(), z2.imag() if x1 < x2: return -1 elif x1 > x2: return 1 elif y1 < y2: return -1 elif y1 > y2: return 1
from sage.all import ComplexIntervalField, RealNumber, ZZ, CDF, prime_pi, prime_divisors, ComplexBallField, RealIntervalField, QQ, prime_powers, PowerSeriesRing, PolynomialRing, prod, spline, srange, gcd, primes_first_n, exp, pi, I, next_prime, Infinity, RR import os, sys, json from dirichlet_conrey import DirichletGroup_conrey, DirichletCharacter_conrey # 265 = 80 digits default_prec = 300 CCC = ComplexBallField(default_prec) RRR = RealIntervalField(default_prec) CIF = ComplexIntervalField(default_prec) def toRRR(elt, drop = True): if "." in elt and len(elt) > 70: # drop the last digit and convert it to an unkown if 'E' in elt: begin, end = elt.split("E") elif 'e' in elt: begin, end = elt.split("E") else: begin = elt end = "0" if drop: begin = begin[:-1] # drop the last digit return RRR(begin + "0e" + end, begin + "9e" + end) else: return RRR(elt) def toCCC(r, i, drop = True): return CCC(toRRR(r, drop)) + CCC.gens()[0]*CCC(toRRR(i, drop)) def print_RRR(elt): if elt.contains_integer(): try: