Example #1
0
    def union(self, interval):
        check_intervals_digits_coincide(self, interval)
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.lower) < mpfr(interval.lower):
                min = self.lower
                include_min = self.include_lower
            elif mpfr(self.lower) > mpfr(interval.lower):
                min = interval.lower
                include_min = interval.include_lower
            else:
                min = interval.lower
                include_min = interval.include_lower or self.include_lower

        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.upper) < mpfr(interval.upper):
                max = interval.upper
                include_max = interval.include_upper
            elif mpfr(self.upper) > mpfr(interval.upper):
                max = self.upper
                include_max = self.include_upper
            else:
                max = self.upper
                include_max = self.include_upper or interval.include_upper
        return Interval(min, max, include_min, include_max, self.digits)
Example #2
0
    def intersection(self, interval):
        check_intervals_digits_coincide(self, interval)
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundToNearest,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.lower) > mpfr(interval.upper) or mpfr(
                    self.upper) < mpfr(interval.lower):
                return empty_interval

        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.lower) > mpfr(interval.upper) or mpfr(
                    self.upper) < mpfr(interval.lower):
                return empty_interval
            if mpfr(self.lower) > mpfr(interval.lower):
                min_bound = self.lower
            else:
                min_bound = interval.lower
            #min_bound=round_number_down_to_digits(max(mpfr(self.lower), mpfr(interval.lower)), self.digits)
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            if mpfr(self.lower) > mpfr(interval.upper) or mpfr(
                    self.upper) < mpfr(interval.lower):
                return empty_interval
            if mpfr(self.upper) < mpfr(interval.upper):
                max_bound = self.upper
            else:
                max_bound = interval.upper
            #max_bound=round_number_up_to_digits(min(mpfr(self.upper),mpfr(interval.upper)), self.digits)
        return Interval(min_bound, max_bound, True, True, self.digits)
Example #3
0
def adjust_ret_list(retlist):
    retlist[0].cdf_low="0.0"
    retlist[-1].cdf_up="1.0"
    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx:
        min_value=gmpy2.exp10(-digits_for_input_cdf)
        current=min_value
    for pbox in retlist:
        with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx:
            if gmpy2.is_zero(gmpy2.mpfr(pbox.cdf_low)) or gmpy2.mpfr(pbox.cdf_low)<current:
                pbox.cdf_low=round_number_down_to_digits(current, digits_for_input_cdf)
                with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx:
                    current=current+min_value
            if gmpy2.is_zero(gmpy2.mpfr(pbox.cdf_up)) or gmpy2.mpfr(pbox.cdf_up)<current:
                pbox.cdf_up=round_number_down_to_digits(current, digits_for_input_cdf)

    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx:
        current=gmpy2.sub(gmpy2.mpfr("1.0"), min_value)
    for pbox in retlist[::-1]:
        with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx:
            if gmpy2.mpfr(pbox.cdf_up)==gmpy2.mpfr("1.0") or gmpy2.mpfr(pbox.cdf_up)>current:
                pbox.cdf_up=round_number_up_to_digits(current, digits_for_input_cdf)
                current=gmpy2.sub(current, min_value)
            if gmpy2.mpfr(pbox.cdf_low)==gmpy2.mpfr("1.0") or gmpy2.mpfr(pbox.cdf_low)>current:
                pbox.cdf_low=round_number_up_to_digits(current, digits_for_input_cdf)

    retlist[0].cdf_low = "0.0"
    retlist[-1].cdf_up = "1.0"

    return retlist
Example #4
0
    def subtraction(self, interval):
        reset_default_precision()
        res_inc_left = False
        res_inc_right = False
        if self.include_lower and interval.include_lower:
            res_inc_left = True
        if self.include_upper and interval.include_upper:
            res_inc_right = True
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundDown,
                                 precision=mpfr_proxy_precision) as ctx:
            res_left = gmpy2.sub(mpfr(self.lower), mpfr(interval.upper))
        with gmpy2.local_context(gmpy2.context(),
                                 round=gmpy2.RoundUp,
                                 precision=mpfr_proxy_precision) as ctx:
            res_right = gmpy2.sub(mpfr(self.upper), mpfr(interval.lower))

        if res_left <= res_right:
            res_right = round_number_up_to_digits(res_right, self.digits)
            res_left = round_number_down_to_digits(res_left, self.digits)
            return Interval(res_left, res_right, res_inc_left, res_inc_right,
                            self.digits)
        else:
            res_right = round_number_down_to_digits(res_right, self.digits)
            res_left = round_number_up_to_digits(res_left, self.digits)
            return Interval(res_right, res_left, res_inc_right, res_inc_left,
                            self.digits)
Example #5
0
def check_interval_is_zero(interval):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundDown,
                             precision=mpfr_proxy_precision) as ctx:
        left = mpfr(interval.lower)
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundUp,
                             precision=mpfr_proxy_precision) as ctx:
        right = mpfr(interval.upper)
    if gmpy2.is_zero(left) and gmpy2.is_zero(right):
        return True
    return False
Example #6
0
 def round_value_to_interval(str_value):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = mpfr(str_value)
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = mpfr(str_value)
     return Interval(
         round_number_down_to_digits(res_left, digits_for_range),
         round_number_up_to_digits(res_right, digits_for_range), True, True,
         digits_for_range)
Example #7
0
def check_sterbenz_apply(interval1, interval2):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundDown,
                             precision=mpfr_proxy_precision) as ctx:
        two_y_left = gmpy2.mul(mpfr("2.0"), mpfr(interval2.lower))
        two_x_left = gmpy2.mul(mpfr("2.0"), mpfr(interval1.lower))
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundUp,
                             precision=mpfr_proxy_precision) as ctx:
        y_right = mpfr(interval2.upper)
        x_right = mpfr(interval1.upper)
    if x_right <= two_y_left and y_right <= two_x_left:
        return True
    return False
Example #8
0
 def compute_middle_point_given_interval(low, upper):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = gmpy2.add(gmpy2.div(mpfr(upper), mpfr("2.0")),
                              gmpy2.div(mpfr(low), mpfr("2.0")))
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = gmpy2.add(gmpy2.div(mpfr(upper), mpfr("2.0")),
                               gmpy2.div(mpfr(low), mpfr("2.0")))
     return Interval(
         round_number_down_to_digits(res_left, digits_for_range),
         round_number_up_to_digits(res_right, digits_for_range), True, True,
         digits_for_range)
Example #9
0
 def compute_uncertainty_given_interval(low, upper):
     coefficients = {}
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = gmpy2.sub(gmpy2.div(mpfr(upper), mpfr("2.0")),
                              gmpy2.div(mpfr(low), mpfr("2.0")))
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = gmpy2.sub(gmpy2.div(mpfr(upper), mpfr("2.0")),
                               gmpy2.div(mpfr(low), mpfr("2.0")))
     coefficients[AffineManager.get_new_error_index()]=\
         Interval(round_number_down_to_digits(res_left, digits_for_range),
                  round_number_up_to_digits(res_right, digits_for_range), True, True, digits_for_range)
     return coefficients
Example #10
0
File: sha2.py Project: mmgen/mmgen
	def initConstants(cls):

		from math import sqrt

		def nextPrime(n=2):
			while True:
				for factor in range(2,int(sqrt(n))+1):
					if n % factor == 0:
						break
				else:
					yield n
				n += 1

		# Find the first nRounds primes
		npgen = nextPrime()
		primes = [next(npgen) for x in range(cls.nRounds)]

		fb_mul = 2 ** cls.wordBits
		def getFractionalBits(n):
			return int((n - int(n)) * fb_mul)

		if cls.use_gmp:
			from gmpy2 import context,set_context,sqrt,cbrt
			set_context(context(precision=75))
		else:
			cbrt = lambda n: pow(n, 1 / 3)

		# First wordBits bits of the fractional parts of the square roots of the first 8 primes
		H = (getFractionalBits(sqrt(n)) for n in primes[:8])

		# First wordBits bits of the fractional parts of the cube roots of the first nRounds primes
		K = (getFractionalBits(cbrt(n)) for n in primes)

		cls.H_init = tuple(H)
		cls.K      = tuple(K)
Example #11
0
def main23(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(6*N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<6*N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        '''print x**2 > s ,  x**2 < s
        while x**2>s:
            x-=1
            print 1,
        print x**2 > s ,  x**2 < s'''
        for p in [(A-x)/2,(A-x)/3,(A+x)/2,(A+x)/3   ]:
            q = N/p
            
            if p*q==N:
                print gmpy2.is_prime(q)
                print gmpy2.is_prime(p)
                print min(p,q)
                assert False,'bla'
Example #12
0
def main(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        print x**2 > s ,  x**2 < s
        '''while x**2>s:
            x-=1
            print 1,'''
        print x**2 > s ,  x**2 < s

        p = A-x
        q = A+x
        q = N/p

        if p*q==N:
            print gmpy2.is_prime(q)
            print gmpy2.is_prime(p)
            print min(p,q)
            break
Example #13
0
def set_prec(prc=None):
    """
    set the precision
    pass None to get current precision
    prc is the number of digits that should be accurate in base two
    """
    #note:
    #  precision is defined in base 2. It needs to be redefined in the base
    #  that is being used so as the number in the new base so it doesn't lose
    #  precision. That is, the number shouldn't return with trailing garbage
    #  (45.0000000000000000052...). The conversions are automatically done in
    #  the functions that need the precision - it is not done here.

    global prec
    if prc is None: return prec
    prc = int(abs(prc))

    if backend == 'mpmath':  # base ten precision
        mp.prec = int(prc * log(2, 10))
    elif backend == 'gmpy2':  # base two precision
        gm.set_context(gm.context(precision=prc))
    elif backend == 'decimal':  # base ten precision
        dm.getcontext().prec = int(prc * log(2, 10))
    else:
        pass

    prec = prc
    return prc
Example #14
0
def check_zero_is_in_interval(interval):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundDown,
                             precision=mpfr_proxy_precision) as ctx:
        left = mpfr(interval.lower)
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundUp,
                             precision=mpfr_proxy_precision) as ctx:
        right = mpfr(interval.upper)
    if gmpy2.is_zero(left) and interval.include_lower:
        return True
    if gmpy2.is_zero(right) and interval.include_upper:
        return True
    if left < mpfr("0.0") < right:
        return True
    return False
Example #15
0
def main():
    gmpy2.set_context(gmpy2.context())
    gmpy2.get_context().precision = 75
    T = int(input())
    if T < 1 or T > 100:
        raise RuntimeError("T is not within the valid range")
    for i in range(T):
        n = int(input())
        r = Numbers(n)
        print("Case #" + str(i + 1) + ": " + r)
Example #16
0
 def add_all_coefficients_upper_abs(self):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundAwayZero,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = mpfr("0.0")
         for coeff in self.coefficients:
             res_right = gmpy2.add(
                 res_right, abs(mpfr(self.coefficients[coeff].upper)))
         # now the number is positive so we can round up
         return round_number_up_to_digits(res_right, digits_for_range)
Example #17
0
def recover_msg(N1, N2, N3, C1, C2, C3):

    m = 42
    # your code starts here: to calculate the original message - m
    # Note 'm' should be an integer
    N = N1 * N2 * N3
    #y1 = N / N1
    #y2 = N / N2
    #y3 = N / N3

    s = [1, 0]
    r = [(N / N1), N1]
    i = 2
    temp = (N / N1) % N1
    while (temp > 0):
        temp = r[i - 2] % r[i - 1]
        r.append(temp)
        s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1])
        i += 1
    z1 = s[i - 2]

    s = [1, 0]
    r = [(N / N2), N2]
    i = 2
    temp = (N / N2) % N2
    while (temp > 0):
        temp = r[i - 2] % r[i - 1]
        r.append(temp)
        s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1])
        i += 1
    z2 = s[i - 2]

    s = [1, 0]
    r = [(N / N3), N3]
    i = 2
    temp = (N / N3) % N3
    while (temp > 0):
        temp = r[i - 2] % r[i - 1]
        r.append(r[i - 2] % r[i - 1])
        s.append(s[i - 2] - (r[i - 2] / r[i - 1]) * s[i - 1])
        i += 1
    z3 = s[i - 2]
    if z1 < 0: z1 += N1
    if z2 < 0: z2 += N2
    if z3 < 0: z3 += N3
    x = (z1 * C1 * (N / N1) + z2 * C2 * (N / N2) + z3 * C3 * (N / N3)) % N
    gmpy2.set_context(gmpy2.context())
    gmpy2.get_context().precision = 1000000
    m = int(gmpy2.cbrt(x))
    # your code ends here

    # convert the int to message string
    msg = hex(m).rstrip('L')[2:].decode('hex')
    return msg
Example #18
0
def createDSIfromDistribution(distribution, n=50):
    #np.logspace(-9, 5, base=2, num=50) spacing should be done by powers of 2
    if distribution.range_()[0]==0.0 and distribution.range_()[-1]==1.0 and use_powers_of_two_spacing:
        lin_space = powers_of_two_spacing()
    elif "FTE" in distribution.name and use_powers_of_two_spacing:
        lin_space = powers_of_two_error(distribution.d.precision)
    else:
        lin_space = np.linspace(distribution.range_()[0], distribution.range_()[-1], num=n + 1, endpoint=True)

    if custom_spacing:
        try:
            lin_space = distribution.get_my_spacing()
        except:
            lin_space = np.linspace(distribution.range_()[0], distribution.range_()[-1], num=n + 1, endpoint=True)

    cdf_distr=distribution.get_piecewise_cdf()
    ret_list=[]
    for i in range(0, len(lin_space)-1):
        with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx:
            lower=round_number_down_to_digits(gmpy2.mpfr(lin_space[i]), digits_for_input_discretization)
        with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx:
            upper=round_number_up_to_digits(gmpy2.mpfr(lin_space[i+1]), digits_for_input_discretization)
        cdf_low_bound=min(1.0, max(0.0, cdf_distr(float(lin_space[i]))))
        cdf_up_bound=min(1.0, max(0.0, cdf_distr(float(lin_space[i+1]))))
        cdf_low_string=dec2Str(round_near(cdf_low_bound, digits_for_input_cdf))
        cdf_up_string=dec2Str(round_near(cdf_up_bound, digits_for_input_cdf))
        pbox = PBox(Interval(lower, upper, True, False, digits_for_range),
                             cdf_low_string, cdf_up_string)
        ret_list.append(pbox)

    ret_list=adjust_ret_list(ret_list)

    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx:
        ret_list[0].interval.lower = \
            round_number_down_to_digits(gmpy2.mpfr(distribution.a_real), digits_for_input_discretization)
    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx:
        ret_list[-1].interval.upper = \
            round_number_up_to_digits(gmpy2.mpfr(distribution.b_real), digits_for_input_discretization)
    ret_list[-1].interval.include_upper = True
    mixarith=MixedArithmetic(ret_list[0].interval.lower,ret_list[-1].interval.upper,ret_list)
    return mixarith
Example #19
0
 def check_zero_is_in_interval(self):
     zero_is_included = False
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         if mpfr(self.lower) < mpfr("0.0") < mpfr(self.upper):
             zero_is_included = True
         if mpfr(self.lower) == mpfr("0.0") and self.include_lower:
             zero_is_included = True
         if mpfr(self.upper) == mpfr("0.0") and self.include_upper:
             zero_is_included = True
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         if mpfr(self.lower) < mpfr("0.0") < mpfr(self.upper):
             zero_is_included = True
         if mpfr(self.lower) == mpfr("0.0") and self.include_lower:
             zero_is_included = True
         if mpfr(self.upper) == mpfr("0.0") and self.include_upper:
             zero_is_included = True
     return zero_is_included
Example #20
0
 def clean_affine_operation(self):
     keys = []
     for key in self.coefficients:
         value = self.coefficients[key]
         remove = [False, False]
         with gmpy2.local_context(gmpy2.context(),
                                  round=gmpy2.RoundDown,
                                  precision=mpfr_proxy_precision) as ctx:
             if gmpy2.is_zero(mpfr(value.lower)):
                 remove[0] = True
         with gmpy2.local_context(gmpy2.context(),
                                  round=gmpy2.RoundUp,
                                  precision=mpfr_proxy_precision) as ctx:
             if gmpy2.is_zero(mpfr(value.upper)):
                 remove[1] = True
         if remove[0] and remove[1]:
             keys.append(key)
     for delete in keys:
         del self.coefficients[delete]
     self.update_interval()
     return self
Example #21
0
def find_min_abs_interval(interval):
    with gmpy2.local_context(gmpy2.context(),
                             round=gmpy2.RoundToZero,
                             precision=mpfr_proxy_precision) as ctx:
        left = abs(mpfr(interval.lower))
        right = abs(mpfr(interval.upper))
    if left < right:
        #Now the number is positive so we can round down
        return round_number_down_to_digits(left, digits_for_range)
    else:
        #Now the number is positive so we can round down
        return round_number_down_to_digits(right, digits_for_range)
Example #22
0
 def compute_interval(self):
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundDown,
                              precision=mpfr_proxy_precision) as ctx:
         res_left = gmpy2.sub(mpfr(self.center.lower),
                              mpfr(self.add_all_coefficients_lower_abs()))
     with gmpy2.local_context(gmpy2.context(),
                              round=gmpy2.RoundUp,
                              precision=mpfr_proxy_precision) as ctx:
         res_right = gmpy2.add(mpfr(self.center.upper),
                               mpfr(self.add_all_coefficients_upper_abs()))
     if res_left <= res_right:
         return Interval(
             round_number_down_to_digits(res_left, digits_for_range),
             round_number_up_to_digits(res_right, digits_for_range), True,
             True, digits_for_range)
     else:
         return Interval(
             round_number_down_to_digits(res_right, digits_for_range),
             round_number_up_to_digits(res_left, digits_for_range), True,
             True, digits_for_range)
Example #23
0
def powers_of_two_spacing():
    exp_spacing=[]
    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundToNearest, precision=mpfr_proxy_precision) as ctx:
        exponent=gmpy2.mpfr("0")
        while abs(exponent)<discretization_points:
            value=gmpy2.exp2(exponent)
            exp_spacing.insert(0, round_number_nearest_to_digits(value, digits_for_input_discretization))
            exponent=gmpy2.sub(exponent,gmpy2.mpfr("1"))
        exp_spacing.insert(0, "0.0")
    for index, value in enumerate(exp_spacing[:-1]):
        if value==exp_spacing[index+1]:
            print("Problem with digits in powers of 2")
            exit(-1)
    return exp_spacing
Example #24
0
    def __init_subclass__(cls, **kwargs):
        if cls.is_bound:
            if cls.ieee_compliance:
                precision = cls.mantissa_size + 1
                emax = 1 << (cls.exponent_size - 1)
                emin = 4 - emax - precision
                subnormalize = True
            else:
                precision = cls.mantissa_size + 1
                emax = 1 << (cls.exponent_size - 1)
                emin = 3 - emax
                subnormalize = False

            ctx = gmpy2.context(
                precision=precision,
                emin=emin,
                emax=emax,
                round=_mode_2_gmpy2[cls.mode],
                subnormalize=cls.ieee_compliance,
                allow_complex=False,
            )

            if hasattr(cls, '_ctx_'):
                c_ctx = cls._ctx_
                if not isinstance(c_ctx, type(ctx)):
                    raise TypeError(
                        'class attribute _ctx_ is reversed by FPVector')
                #stupid compare because contexts aren't comparable
                elif (c_ctx.precision != ctx.precision
                      or c_ctx.real_prec != ctx.real_prec
                      or c_ctx.imag_prec != ctx.imag_prec
                      or c_ctx.round != ctx.round
                      or c_ctx.real_round != ctx.real_round
                      or c_ctx.imag_round != ctx.imag_round
                      or c_ctx.emax != ctx.emax or c_ctx.emin != ctx.emin
                      or c_ctx.subnormalize != ctx.subnormalize
                      or c_ctx.trap_underflow != ctx.trap_underflow
                      or c_ctx.trap_overflow != ctx.trap_overflow
                      or c_ctx.trap_inexact != ctx.trap_inexact
                      or c_ctx.trap_erange != ctx.trap_erange
                      or c_ctx.trap_divzero != ctx.trap_divzero
                      or c_ctx.trap_expbound != ctx.trap_expbound
                      or c_ctx.allow_complex != ctx.allow_complex):
                    # this basically should never happen unless some one does
                    # class Foo(FPVector):
                    #   _ctx_ = gmpy2.context(....)
                    raise TypeError('Incompatible context types')

            cls._ctx_ = ctx
Example #25
0
def powers_of_two_error(precision):
    exp_spacing=[]
    with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundToNearest, precision=mpfr_proxy_precision) as ctx:
        exponent=gmpy2.mpfr(-precision)
        counter=0
        while counter<discretization_points//2:
            value=gmpy2.exp2(exponent)
            exp_spacing.insert(0, round_number_nearest_to_digits(value, digits_for_input_discretization))
            exponent=gmpy2.sub(exponent,gmpy2.mpfr("1"))
            counter=counter+1
    exp_spacing_reverse=copy.deepcopy(exp_spacing)
    exp_spacing_reverse.reverse()
    exp_spacing_reverse=["-"+s for s in exp_spacing_reverse]
    exp_spacing=exp_spacing_reverse+["0.0"]+exp_spacing
    for index, value in enumerate(exp_spacing[:-1]):
        if value==exp_spacing[index+1]:
            print("Problem with digits in powers of 2")
            exit(-1)
    return exp_spacing
def calculate_curve_constants():
    """
    Calculate the curve constants $\ell_i$
    :return:
    """
    expected_values = [
        50127518246259276682880317011538934615153226543083896339791,
        22358026531042503310338016640572204942053343837521088510715,
        5105580562119000402467322500999592531749084507000101675068,
        19494034873545274265741574254707851381713530791194721254848
    ]
    ells = []
    alpha_hats = calculate_alpha_hats()
    gmpy2.context().real_round = gmpy2.RoundToNearest
    for i in range(4):
        alpha_hat_i = alpha_hats[i]
        ell_i = round(mpq(alpha_hat_i * mu, N))
        # Verify results what precomputed values
        assert ell_i == expected_values[i]
        ells.append(ell_i)
    return ells
Example #27
0
    def initConstants(cls):

        from math import sqrt

        def nextPrime(n=2):
            while True:
                for factor in range(2, int(sqrt(n)) + 1):
                    if n % factor == 0:
                        break
                else:
                    yield n
                n += 1

        # Find the first nRounds primes
        npgen = nextPrime()
        primes = [next(npgen) for x in range(cls.nRounds)]

        fb_mul = 2**cls.wordBits

        def getFractionalBits(n):
            return int((n - int(n)) * fb_mul)

        if cls.use_gmp:
            from gmpy2 import context, set_context, sqrt, cbrt
            # context() parameters are platform-dependent!
            set_context(context(precision=75,
                                round=1))  # OK for gmp 6.1.2 / gmpy 2.1.0
        else:
            cbrt = lambda n: pow(n, 1 / 3)

        # First wordBits bits of the fractional parts of the square roots of the first 8 primes
        H = (getFractionalBits(sqrt(n)) for n in primes[:8])

        # First wordBits bits of the fractional parts of the cube roots of the first nRounds primes
        K = (getFractionalBits(cbrt(n)) for n in primes)

        cls.H_init = tuple(H)
        cls.K = tuple(K)
Example #28
0
import gmpy2
from gmpy2 import mpfr, const_pi, const_euler
from numpy import meshgrid, array

import matplotlib.pyplot as plt
import seaborn as sns

import matplotlib.animation as anim

import os
import cv2  # conda install -c conda-forge opencv=4.1.0

bits = 32
# bits = 64

gmpy2.set_context(gmpy2.context(precision=bits))

# ------------------------------------------------
### FUNCTIONS ###


def mp(num):
    return mpfr(str(num))


def backf(num, digits=5):
    return float(round(num, digits))


def listf(l):
    return list(map(backf, l))
Example #29
0
def regions_binary(ra, rd, pf_plus, pf_minus, precision=1000):
    """
    Construct (px, px_tilde, px/px_tilde) regions used to find the certified radius for binary data.

    Intuitively, pf_minus controls rd and pf_plus controls ra.

    Parameters
    ----------
    ra: int
        Number of ones y has added to x
    rd : int
        Number of ones y has deleted from x
    pf_plus : float, 0 <= p_plus <= 1
        The probability to flip a zero to a one
    pf_minus: float, 0 <= p_plus <= 1
        The probability to flip a one to a zero
    precision: int
        Numerical precision for floating point calculations

    Returns
    -------
    regions: array-like, [None, 3]
        Regions of constant probability under px and px_tilde,
    """

    pf_plus, pf_minus = gmpy2.mpfr(pf_plus), gmpy2.mpfr(pf_minus)
    with gmpy2.context(precision=precision):
        if pf_plus == 0:
            px = pf_minus**rd
            px_tilde = pf_minus**ra

            return np.array([[1 - px, 0, float('inf')],
                             [px, px_tilde, px / px_tilde],
                             [0, 1 - px_tilde, 0]])

        if pf_minus == 0:
            px = pf_plus**ra
            px_tilde = pf_plus**rd
            return np.array([
                [1 - px, 0, float('inf')],
                [px, px_tilde, px / px_tilde],
                [0, 1 - px_tilde, 0],
            ])
        max_q = ra + rd
        i_vec = np.arange(0, max_q + 1)

        T = ra * ((pf_plus / (1 - pf_plus)) ** i_vec) + \
            rd * ((pf_minus / (1 - pf_minus)) ** i_vec)

        ratio = np.zeros_like(T)
        px = np.zeros_like(T)
        px[0] = 1

        for q in range(0, max_q + 1):
            ratio[q] = (pf_plus/(1-pf_minus)) ** (q - rd) * \
                (pf_minus/(1-pf_plus)) ** (q - ra)

            if q == 0:
                continue

            for i in range(1, q + 1):
                px[q] = px[q] + ((-1)**(i + 1)) * T[i] * px[q - i]
            px[q] = px[q] / q

        scale = ((1 - pf_plus)**ra) * ((1 - pf_minus)**rd)

        px = px * scale

        regions = np.column_stack((px, px / ratio, ratio))
        if pf_plus + pf_minus > 1:
            # reverse the order to maintain decreasing sorting
            regions = regions[::-1]
        return regions
Example #30
0
def regions_discrete(ra, rd, rc, k, pf_plus, pf_minus, precision=1000):
    """
    Construct (px, px_tilde, px/px_tilde) regions used to find the certified radius for general discrete data.

    Note: if pf_plus = pf_minus any combination of ra+rd+rc=r gives the same result.

    ra: int
        Number of zeros changed to non-zeros from x to x_tilde.
    rd : int
        Number of non-zeros changed to zeros from x to x_tilde.
    rc : int
        Number of non-zeros changed to other non-zero values from x to x_tilde.
    k: int
        Number of discrete categories.
    pf_plus : float, 0 <= p_plus <= 1
        The probability to flip a zero to a non-zero.
    pf_minus: float, 0 <= p_plus <= 1
        The probability to flip a non-zero to a zero.
    precision: int
        Numerical precision for floating point calculations.
    """
    with gmpy2.context(precision=precision):
        pf_plus, pf_minus = gmpy2.mpfr(pf_plus), gmpy2.mpfr(pf_minus)
        one = gmpy2.mpfr(1)

    ra, rd, rc = int(ra), int(rd), int(rc)

    a0 = (one - pf_plus)
    b0 = pf_plus / (k - 1)
    c0 = one - a0 - b0
    dist_0 = [a0, b0, c0]

    a1 = (one - pf_minus)
    b1 = pf_minus / (k - 1)
    c1 = one - a1 - b1
    dist_1 = [a1, b1, c1]

    regions = defaultdict(float)
    for triplet in product(triplets(ra, k), triplets(rd, k), triplets(rc, k)):
        q0, p0, m0 = triplet[0]
        q1, p1, m1 = triplet[1]
        q2, p2, m2 = triplet[2]

        ratio = 1
        ratio *= (a0 / b1)**(q0 - p1)
        ratio *= (b0 / a1)**(p0 - q1)
        ratio *= (c0 / c1)**(m0 - m1)
        ratio *= (a1 / b1)**(q2 - p2)

        # compute the product of three multinomial distributions
        px = 1
        for (qi, pi, mi), ri, dist in zip(triplet, [ra, rd, rc],
                                          [dist_0, dist_1, dist_1]):
            px *= dist[0]**qi
            px *= dist[1]**pi
            px *= dist[2]**mi
            px *= gmpy2.fac(ri) / gmpy2.fac(qi) / gmpy2.fac(pi) / gmpy2.fac(mi)

        regions[float(ratio)] += px

    regions = np.array(list(regions.items()))
    srt = regions[:, 0].argsort()[::-1]

    return np.column_stack(
        (regions[srt, 1], regions[srt, 1] / regions[srt, 0], regions[srt, 0]))
Example #31
0
cipher = 2780321436921227845269766067805604547641764672251687438825498122989499386967784164108893743279610287605669769995594639683212592165536863280639528420328182048065518360606262307313806591343147104009274770408926901136562839153074067955850912830877064811031354484452546219065027914838811744269912371819665118277221
n = 23571113171923293137414347535961677173798389971011031071091131271311371391491511571631671731791811911931971992112232272292332392412512572632692712772812832933073113133173313373473493533593673733793833893974014094194214314334394434494574614634674794874914995035095215235415475575635695715775875935996016076136176196316416436476536596616736776836917017097197277337397437517577617697737877978098118218238278298398538578598638778818838879079119199299379419479539679719779839919971009101310191431936117404941729571877755575331917062752829306305198341421305376800954281557410379953262534149212590443063350628712530148541217933209759909975139820841212346188350112608680453894647472456216566674289561525527394398888860917887112180144144965154878409149321280697460295807024856510864232914981820173542223592901476958693572703687098161888680486757805443187028074386001621827485207065876653623459779938558845775617779542038109532989486603799040658192890612331485359615639748042902366550066934348195272617921683

Low Public Exponent Attack
"""

import sys
try:
    import gmpy2
except ImportError:
    print("Install gmpy2 first to run this program")
    sys.exit()

e = 3
cipher = 2780321436921227845269766067805604547641764672251687438825498122989499386967784164108893743279610287605669769995594639683212592165536863280639528420328182048065518360606262307313806591343147104009274770408926901136562839153074067955850912830877064811031354484452546219065027914838811744269912371819665118277221
n = 23571113171923293137414347535961677173798389971011031071091131271311371391491511571631671731791811911931971992112232272292332392412512572632692712772812832933073113133173313373473493533593673733793833893974014094194214314334394434494574614634674794874914995035095215235415475575635695715775875935996016076136176196316416436476536596616736776836917017097197277337397437517577617697737877978098118218238278298398538578598638778818838879079119199299379419479539679719779839919971009101310191431936117404941729571877755575331917062752829306305198341421305376800954281557410379953262534149212590443063350628712530148541217933209759909975139820841212346188350112608680453894647472456216566674289561525527394398888860917887112180144144965154878409149321280697460295807024856510864232914981820173542223592901476958693572703687098161888680486757805443187028074386001621827485207065876653623459779938558845775617779542038109532989486603799040658192890612331485359615639748042902366550066934348195272617921683
n = hex(n)

import gmpy2

with gmpy2.local_context(gmpy2.context(), precision=800) as ctx:
    ctx.precision += 800
    root = gmpy2.cbrt(cipher)

try:
    print(str('%x' % +int(root)).decode('hex'))
except AttributeError:
    print(bytes.fromhex(str('%x' % +int(root))).decode('utf-8'))

# answer!!
# dsc{t0-m355-w1th-m4th-t4k35-4-l0t-0f-sp1n3}
Example #32
0
import gmpy2
from gmpy2 import mpz

__author__ = 'Qubo'

N1 = '17976931348623159077293051907890247336179769789423065727343008115'
N1 += '77326758055056206869853794492129829595855013875371640157101398586'
N1 += '47833778606925583497541085196591615128057575940752635007475935288'
N1 += '71082364994994077189561705436114947486504671101510156394068052754'
N1 += '0071584560878577663743040086340742855278549092581'

gmpy2.set_context(gmpy2.context(precision=2000))

N = mpz(N1)
A = gmpy2.ceil(gmpy2.sqrt(N))
SquareA = gmpy2.square(A)

if gmpy2.is_square(mpz(gmpy2.sub(SquareA, N))):
    x = gmpy2.sqrt(gmpy2.sub(SquareA, N))
    print 'p = ' + str(mpz(gmpy2.sub(A, x)))
    print 'q = ' + str(mpz(gmpy2.add(A, x)))
else:
    print 'x is not square, must be wrong...'
Example #33
0
# ------------------------------------------------
### IMPORTS ###

from gmpy2 import context, set_context
from gmpy2 import mpfr, sqrt, const_pi, exp, sin, cos, polar, norm

import matplotlib.pyplot as plt
from seaborn import set_style

# ------------------------------------------------
### DEFINITIONS ###

set_style('darkgrid')

bits = 64
set_context(context(precision=bits, allow_complex=True))

I = sqrt(-1)

pi = const_pi(bits)

# ------------------------------------------------
### FUNCTIONS ###


def backf(val, digits=8):
    return [backf(v, digits)
            for v in val] if isinstance(val,
                                        (list, tuple, map,
                                         zip)) else float(round(val, digits))
Example #34
0
out = partial(print, sep='\n', end='\n\n')

if __name__ == '__main__':
    # Reales de precisión arbitraria
    # En el siguiente ejemplo se muestra con la precisión normal
    out ('Raíz de dos: ', gmpy2.sqrt(2))

    # Obtenemos la precisión máxima teórica de la computadora
    out ('Precisión máxima: ', gmpy2.get_max_precision())

    # ¿Cuál es la precisión por defecto?
    out ('Precisión por defecto', gmpy2.get_context().precision)

    # Cambiamos la precisión de la biblioteca
    gmpy2.get_context().precision=100

    # Otra vez la raíz de dos, con precisión aumentada
    out ('Raíz de dos: ', gmpy2.sqrt(2))
    # De hecho es la precisión de cualquier número
    out ('Un flotante: ', mpfr('1.2'))

    # Ahora creamos un contexto para manejar la precisión
    with gmpy2.local_context(gmpy2.context(), precision=200) as ctx:
        out ('Precisión alterada en contexto', gmpy2.sqrt(2))
        ctx.precision += 100
        out ('Aún mejor precision', gmpy2.sqrt(2))

    # De regreso al contexto original, precision normal
    out ('Raíz de dos', gmpy2.sqrt(2))
Example #35
0

def mp(num):
    return mpfr(str(num))


def backf(num, digits=5):
    return float(round(num, digits))

def listf( l ):
    return list(map(backf, l))

# ------------------------------------------------
### TESTS ###

gmpy2.set_context(gmpy2.context(precision=32))


# for the 1st order Euler EDO method

dy_dt = lambda t, y: 4*t - (2/t)*y
t_0 = mp(1)
y_0 = mp(2)
dt = 8*mp(10)**-3
interv = [mp(0.2), mp(1.8)]

sol1_t = arange( *interv, dt)
sol1_y = list(map(lambda t: t**2 + 1/(t**2), sol1_t))

[apr1_t , apr1_y] = [listf(l) for l in edo1(dy_dt, t_0, y_0, dt, interv)]
Example #36
0
import uuid
import gmpy2
import os.path
import traceback
import __builtin__
from glob import glob

from HALapi import get_main_dir, module_filter, HALcannotHandle

# Some version of gmpy2 doesn't have pow()
try:
    gmpy2.pow(2, 10)
except (AttributeError, TypeError):
    gmpy2.pow = lambda x, y: x**y

gmpy2.context().precision = 256

math_list = ['acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'exp', 'floor', 'fmod', 'hypot', 'modf', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
builtin_list = ['abs']

funcs = dict((name, getattr(gmpy2, name)) for name in math_list)
funcs.update(dict((name, getattr(__builtin__, name)) for name in builtin_list))
funcs.update(fact=math.factorial, mpfr=gmpy2.mpfr, arctan=gmpy2.atan, arccos=gmpy2.acos, arcsin=gmpy2.asin, log=gmpy2.log10,
             ln=gmpy2.log)
const = dict(e =gmpy2.mpfr('2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274'),
             pi=gmpy2.mpfr('3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679'))
filters = {
    '^': '**',
    re.compile(r'([0-9]+)!'): lambda m: 'fact(%s)'%m.group(1),
}
Example #37
0
import gmpy2 
import binascii

ctx = gmpy2.context(precision=10000000,round=gmpy2.RoundUp)
gmpy2.set_context(ctx)


def FermatFactor(N):
  A = gmpy2.mpz( gmpy2.ceil( gmpy2.sqrt(N) ) )
  B2 = gmpy2.sub( gmpy2.square(A), N )

  while not gmpy2.is_square(B2): 
    A = gmpy2.add( A, gmpy2.mpz("1") )
    B2 = gmpy2.sub( gmpy2.square(A), N )
  
  B = gmpy2.sqrt(B2)
  P = gmpy2.mpz( gmpy2.sub( A, B ) )
  Q = gmpy2.mpz( gmpy2.add( A, B ) )
  if not checkFactors(P,Q,N):
    raise Exception("Bad factors generated")
  return ( P, Q )

def checkFactors(p,q,N):
  x = gmpy2.f_mod( N, p )
  y = gmpy2.f_mod( N, q )
  zero = gmpy2.mpz('0')
  if g.is_prime(p) and g.is_prime(q):
    return N == g.mul(p,q) and x == zero and y == zero
  return False

def checkD(e,d,phi):
Example #38
0
import gmpy2 as g
import binascii
import sys

ctx = g.context(precision=10000000,round=g.RoundUp)
g.set_context(ctx)

def bruteSmall(N):
  zero = g.mpz(0)
  two = g.mpz(2)
  if g.f_mod(N, two) == zero:
    return two, g.mpz(g.div(N, two))

  i = g.mpz(3)
  while True:
    if g.f_mod(N, i) == zero:
      p = g.mpz(i)
      q = g.mpz( g.div(N,i) )
      if checkFactors(p,q,N) :
        return p,q
    i = g.add(i, two)

def checkFactors(p,q,N):
  x = g.f_mod( N, p )
  y = g.f_mod( N, q )
  zero = g.mpz('0')
  if g.is_prime(p) and g.is_prime(q):
    return N == g.mul(p,q) and x == zero and y == zero
  return False

def checkD(e,d,phi):