Пример #1
0
def get_binary(minval, maxval):
    assert minval != maxval
    interval_to_encode = Interval(minval, maxval)
    binary_string = ""
    binary_interval = Interval(mpf(0), mpf(1))
    while True:
        zero_option = incremental_interval(binary_interval, 0)
        one_option = incremental_interval(binary_interval, 1)

        if interval_to_encode.overlap(
                zero_option) and interval_to_encode.overlap(one_option):
            interval_to_encode._start = one_option._start

        if interval_to_encode.subset(one_option):
            binary_string += "1"
            binary_interval = one_option
            binary_point = one_option._start
        else:
            binary_string += "0"
            binary_interval = zero_option
            binary_point = zero_option._start

        if point_only:
            if binary_point in interval_to_encode:
                break
        else:
            if binary_interval.subset(interval_to_encode):
                break
    return binary_string
Пример #2
0
 def test_addition(self):
     bits = 512
     base = 10
     one = mpf('1', bits, base)
     eps = mpf('1e-38', bits, base)
     # self.assert_(mpz(1.0/((one+eps)-one)) == 1e+38)
     self.assert_(mpz(1.0 / ((one + eps) - one)) == mpz(10)**38)
Пример #3
0
 def __init__(self, start, end):
     "Construct, start must be <= end."
     if start > end:
         raise ValueError('Start (%s) must not be greater than end (%s)' %
                          (start, end))
     self._start = mpf(start)
     self._end = mpf(end)
Пример #4
0
 def test_equal_to_bits_prec(self):
     bits = 4
     num = mpf('1.0', bits) + 1.0 / mpf(1 << (bits + 1), bits)
     for i in xrange(bits * 2):
         if i <= bits:
             self.assert_(equal_to_bits_prec(1.0, num, i))
         else:
             self.assert_(not equal_to_bits_prec(1.0, num, i))
Пример #5
0
def interval_from_binary_string(binary_string):
    minval = mpf(0)
    maxval = mpf(1)
    for c in binary_string:
        delta = maxval - minval
        n = mpf(c)
        maxval = minval + ((n + 1) / 2) * delta
        minval = minval + (n / 2) * delta
    return Interval(minval, maxval)
Пример #6
0
 def test_make_one(self):
     bits = 128
     base = 10
     ones = []
     ones.append(mpf('1.0', bits, base))
     ones.append(mpf(1.0, bits))
     ones.append(mpf(1.0))
     for one in ones:
         self.assert_(one == 1.0)
Пример #7
0
 def test_make_one_plus_epsilon(self):
     bits = 128
     base = 10
     one = mpf('1', bits, base)
     eps = mpf('1e-38', bits, base)
     self.assert_(one != eps)
     self.assert_(eps > 0.0)
     self.assert_(one + eps > 1.0)
     self.assert_(float(one + eps) == 1.0)
Пример #8
0
 def test_im(self):
     fraction_list = [mpf(2)**(-1*i) for i in range(150)]
     print(fraction_list[2])
     delta = mpf(2)**(-100)
     i = 1
     x = mpf(1/2)
     while True:
         x *= mpf(1/2)
         if delta >= x:
             break
         else:
             i += 1
Пример #9
0
def subdivide(dx, dy):
    iters =  request.args.get("iters", "10")
    x = request.args.get("x", "0")
    y = request.args.get("y", "0")
    wid = request.args.get("wid", "2")
    gwid=gmpy.mpf(wid)
    dx = ((int(dx)/float(SIZE)) - 0.5) * (gwid)
    dy = ((int(dy)/float(SIZE)) - 0.5) * (gwid)
    gx = gmpy.mpf(x) + dx
    gy = gmpy.mpf(y) + dy
    gwid/=2
    return redirect("/?iters=%s&x=%s&y=%s&wid=%s" % (iters, str(gx), str(gy), str(gwid)))
def test(n=100*1000):
    print("Sum of %d items of various types:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Sum of %d items of various types w/2.3 sum builtin:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum1(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Mul of %d items of various types:" % (n//5))
    for z in 1, 1.0, gmpy.mpz(1), gmpy.mpf(1):
        tip, tim, tot = timedmul(n//5, z)
        print("    %5.3f %s" % (tim, tip))
Пример #11
0
def GMPYContext( prec ):
    """Create new GMPY context.
    GMPY settings can be changed, so re-creating this context as needed
    """
    eps = gmpy.mpf(2, prec) ** (-prec + 3)
    return NumericContext(
        one=gmpy.mpf(1,prec),
        zero=gmpy.mpf(0, prec),
        fabs=abs,
        sqrt=gmpy.fsqrt,
        from_int = lambda x: gmpy.mpf(x, prec),
        eps = eps
        )
Пример #12
0
def pan_view(real, imag, wid, iters, direction):
    greal = gmpy.mpf(real)
    gimag = gmpy.mpf(imag)
    gwid=gmpy.mpf(wid)
    if direction == "up":
        gimag -= gwid/2
    elif direction == "down":
        gimag += gwid/2
    elif direction == "left":
        greal -= gwid/2
    elif direction == "right":
        greal += gwid/2
    return redirect("/explore/%s/%s/%s/%s/" % (greal, gimag, gwid, iters))
Пример #13
0
def test(n=100 * 1000):
    print("Sum of %d items of various types:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Sum of %d items of various types w/2.3 sum builtin:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum1(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Mul of %d items of various types:" % (n // 5))
    for z in 1, 1.0, gmpy.mpz(1), gmpy.mpf(1):
        tip, tim, tot = timedmul(n // 5, z)
        print("    %5.3f %s" % (tim, tip))
Пример #14
0
def out(ratio):
    iters = int(request.args.get("iters", "10"))
    x = request.args.get("x", "0")
    y = request.args.get("y", "0")
    wid = request.args.get("wid", "2")

    target_wid = gmpy.mpf(wid)
    gx = gmpy.mpf(x)
    gy = gmpy.mpf(y)
    wid=gmpy.mpf(6)

    

    return "%s, %s, %s, %i" % (x, y, wid, iters)
Пример #15
0
def scale_view(real, imag, wid, iters, new_x, new_y, ratio):
    new_x = float(new_x)
    new_y = float(new_y)
    ratio = float(ratio)
    gwid=gmpy.mpf(wid)

    greal = gmpy.mpf(real)
    gimag = gmpy.mpf(imag)

    greal += (gwid * new_x)
    gimag += (gwid * new_y)

    gwid *= ratio
    return redirect("/explore/%s/%s/%s/%s/" % (greal, gimag, gwid, iters))
Пример #16
0
def get_encoding_length(nfa, parse_result):
    minval = mpf(0)
    maxval = mpf(1)
    states_path, outputs_path = parse_result
    for i, current_state in enumerate(states_path[:-1]):
        segment_terminal_state_tuple = (outputs_path[i], states_path[i + 1])
        length = len(nfa.probabilities[current_state])
        index = nfa.probabilities[current_state].index(
            segment_terminal_state_tuple)
        prob_range = (index / length, (index + 1) / length)
        delta = maxval - minval
        maxval = minval + prob_range[1] * delta
        minval = minval + prob_range[0] * delta
    return len(get_binary(minval, maxval))
Пример #17
0
def fermat_factor(N, minutes=10, verbose=False):
   """
   Code based on Sage code from FactHacks, a joint work by
   Daniel J. Bernstein, Nadia Heninger, and Tanja Lange.

   http://facthacks.cr.yp.to/
   
   N - integer to attempt to factor using Fermat's Last Theorem
   minutes - number of minutes to run the algorithm before giving up
   verbose - (bool) Periodically show how many iterations have been
      attempted
   """
   from time import time
   current_time = int(time())
   end_time = current_time + int(minutes * 60)

   def sqrt(n):
      return gmpy.fsqrt(n)
  
   def is_square(n):
      sqrt_n = sqrt(n)
      return sqrt_n.floor() == sqrt_n

   if verbose:
      print "Starting factorization..."
   
   gmpy.set_minprec(4096)

   N = gmpy.mpf(N)
   if N <= 0:        return [1,N]
   if N % 2 == 0:    return [2,N/2]

   a = gmpy.mpf(gmpy.ceil(sqrt(N)))
   count = 0

   while not is_square(gmpy.mpz(a ** 2 - N)):
      a += 1
      count += 1
      if verbose:
         if (count % 1000000 == 0):
            sys.stdout.write("\rCurrent iterations: %d" % count)
            sys.stdout.flush()
      if time() > end_time:
         if verbose: print "\nTime expired, returning [1,N]"
         return [1,N]

   b = sqrt(gmpy.mpz(a ** 2 - N))
   print "\nModulus factored!"
   return [long(a - b), long(a + b)]
Пример #18
0
def fermat_factor(N, minutes=10, verbose=False):
   """
   Code based on Sage code from FactHacks, a joint work by
   Daniel J. Bernstein, Nadia Heninger, and Tanja Lange.

   http://facthacks.cr.yp.to/
   
   N - integer to attempt to factor using Fermat's Last Theorem
   minutes - number of minutes to run the algorithm before giving up
   verbose - (bool) Periodically show how many iterations have been
      attempted
   """
   from time import time
   current_time = int(time())
   end_time = current_time + int(minutes * 60)

   def sqrt(n):
      return gmpy.fsqrt(n)
  
   def is_square(n):
      sqrt_n = sqrt(n)
      return sqrt_n.floor() == sqrt_n

   if verbose:
      print "Starting factorization..."
   
   gmpy.set_minprec(4096)

   N = gmpy.mpf(N)
   if N <= 0:        return [1,N]
   if N % 2 == 0:    return [2,N/2]

   a = gmpy.mpf(gmpy.ceil(sqrt(N)))
   count = 0

   while not is_square(gmpy.mpz(a ** 2 - N)):
      a += 1
      count += 1
      if verbose:
         if (count % 1000000 == 0):
            sys.stdout.write("\rCurrent iterations: %d" % count)
            sys.stdout.flush()
      if time() > end_time:
         if verbose: print "\nTime expired, returning [1,N]"
         return [1,N]

   b = sqrt(gmpy.mpz(a ** 2 - N))
   print "\nModulus factored!"
   return [long(a - b), long(a + b)]
Пример #19
0
def betweenpts(A1,A2,Q,threshold=0.0000001):
    compAxMin = gmpy.mpf(min(A1.x,A2.x) - gmpy.mpf(threshold));
    compAxMax = gmpy.mpf(max(A1.x,A2.x) + gmpy.mpf(threshold));
    compAyMin = gmpy.mpf(min(A1.y,A2.y) - gmpy.mpf(threshold));
    compAyMax = gmpy.mpf(max(A1.y,A2.y) + gmpy.mpf(threshold));
    if compAxMin <= Q.x <= compAxMax and compAyMin <= Q.y <= compAyMax:
        return True
    return False
Пример #20
0
    def test_can_pickle_string_and_retrieve(self):
        bits = 512
        base = 10
        num = mpf('3.23987239874534573452439582735234e-10', bits, base)
        one = mpf('1', bits, base)
        num = num + one

        def mpf_to_pkl(mpf):
            return (mpf.digits(), mpf.getrprec())

        def pkl_to_mpf((digit_str, prec)):
            return mpf(digit_str, prec, 10)

        s = pickle.dumps(mpf_to_pkl(num))
        num_new = pkl_to_mpf(pickle.loads(s))
        self.assert_(equal_to_bits_prec(num, num_new, bits))
Пример #21
0
 def _laguerre(self, coeff, x, max_iter=1000):
     order = len(coeff) - 1
     for i in range(max_iter):
         p = coeff[-1]
         p1 = 0
         p2 = 0
         err = abs(p)
         absx = abs(x)
         for n in range(order - 1, -1, -1):
             p2 = x * p2 + p1
             p1 = x * p1 + p
             p = x * p + coeff[n]
             err = absx * err + abs(p)
         if abs(p) <= mpf('1.e-30', self.precision) * err:
             return x
         g = p1 / p
         h = g * g - p2 / p
         sq = ((order - 1) * (order * h - g * g)).sqrt()
         gp = g + sq
         gm = g - sq
         if abs(gp) < abs(gm):
             dx = order / gm
         else:
             dx = order / gp
         xnew = x - dx
         if xnew == x:
             return x
         if i % 10 == 9:
             x = x - (i / 10) * dx
         else:
             x = xnew
     raise ValueError, "too many iterations"
def test(n=100*1000):
    print("%dth Fibonacci number of various types:" % n)
    for z in 0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedfib(n, z)
        print("    %5.3f %s %s" % (tim, gmpy.fdigits(tot,10,6), tip))
    tip, tim, tot = timedfibsp(n, 1)
    print("    %5.3f %s %s" % (tim, gmpy.fdigits(tot,10,6), "gmpy.fib"))
Пример #23
0
def period(num, pure_fraction):
    precision = 10000
    str_num = str(gmpy.mpf(1.0, precision) / gmpy.mpf(num, precision))
    fraction = str()

    for i in xrange(len(str_num)):
        if str_num[i] == '.':
            fraction = str_num[i + 1:]
    if pure_fraction:
        #print segment_repeat(fraction)
        return segment_repeat(fraction)        
    else:
        fraction = fraction[len(str(num)):]
        #print fraction
        #print segment_repeat(fraction)
        return segment_repeat(fraction)
Пример #24
0
def Float(num,precision=64):
    "Either a builtin float, or a GMP-based bigfloat, if required and supported"
    if precision > 64:
        if has_bigmath:
            return gmpy.mpf(num,precision)
        else:
            raise PrecisionError()        
    return float(num)
Пример #25
0
def encode_message_over_alphabet(message, alphabet, log_estimate=False):
    '''for testing'''
    if not log_estimate:
        minval = mpf(0)
        maxval = mpf(1)
        length = len(alphabet)
        for char in message:
            delta = maxval - minval
            if char not in alphabet:
                raise ValueError("char in message not in alphabet")
            index = alphabet.index(char)
            prob_range = (index / length, (index + 1) / length)
            maxval = minval + prob_range[1] * delta
            minval = minval + prob_range[0] * delta
        return len(get_binary(minval, maxval))
    else:
        return len(message) * -log(2, 1 / len(alphabet))
Пример #26
0
def incremental_interval(interval, int_):
    minval = interval._start
    maxval = interval._end
    delta = maxval - minval
    n = mpf(int_)
    maxval = minval + ((n + 1) / 2) * delta
    minval = minval + (n / 2) * delta
    return Interval(minval, maxval)
Пример #27
0
 def test_cannot_pickle_and_unpickle_in_raw_form(self):
     bits = 512
     base = 10
     one = mpf('1', bits, base)
     try:
         s = pickle.dumps(one)
     except pickle.PicklingError:
         pass
     else:
         assert 0, 'expected not to be able to pickle in gmpy! new version?'
Пример #28
0
def rama(nsteps,prec=10):
    from gmpy import mpf
    pre = mpf('8',prec).sqrt()/mpf('9801',prec)
    sum = mpf('0',prec)
    for i in range(nsteps):
        num = fact(4*i)*(1103+26390*i)
        den = pow(fact(i),4)*pow(396,4*i)
        sum += mpf(num,prec)/mpf(den,prec)
    print mpf(1,prec)/(pre*sum)
Пример #29
0
def fibonacci_term_number(length):
    '''
    Find Fibonacci's term number for number that contains over (length) digits
    '''
    index = long(1)
    #Initial step divisor value
    step_div = 1
    num = gmpy.mpz(0)
    while gmpy.numdigits(num) != length:

        golden_ratio = gmpy.mpf(((1 + gmpy.fsqrt(5)) / 2)**gmpy.mpf(index) / gmpy.fsqrt(5))
        num = gmpy.mpz(gmpy.fround(golden_ratio, 0))

        if gmpy.numdigits(num) < length:
            index += length / step_div
        #If the previous step was too large, then we go back and reduce it to 2 times
        if gmpy.numdigits(num) > length:
            index -= length / step_div
            step_div *= 2
    return index
Пример #30
0
def do_cmp(x1, x2):
    real1, real2 = x1.get_real_value(), x2.get_real_value()
    inf1 = inf2 = None
    if x1.has_form('DirectedInfinity', 1): inf1 = x1.leaves[0].get_int_value()
    if x2.has_form('DirectedInfinity', 1): inf2 = x2.leaves[0].get_int_value()

    if real1 is not None and get_type(real1) != 'f': real1 = mpf(real1)
    if real2 is not None and get_type(real2) != 'f': real2 = mpf(real2)
    # Bus error when not converting to mpf

    if real1 is not None and real2 is not None:
        return cmp(x1, x2)
    elif inf1 is not None and inf2 is not None:
        return cmp(inf1, inf2)
    elif inf1 is not None and real2 is not None:
        return inf1
    elif real1 is not None and inf2 is not None:
        return -inf2
    else:
        return None
Пример #31
0
def do_cmp(x1, x2):
    real1, real2 = x1.get_real_value(), x2.get_real_value()
    inf1 = inf2 = None
    if x1.has_form('DirectedInfinity', 1): inf1 = x1.leaves[0].get_int_value()
    if x2.has_form('DirectedInfinity', 1): inf2 = x2.leaves[0].get_int_value()
    
    if real1 is not None and get_type(real1) != 'f': real1 = mpf(real1)
    if real2 is not None and get_type(real2) != 'f': real2 = mpf(real2)    
    # Bus error when not converting to mpf
    
    if real1 is not None and real2 is not None:
        return cmp(x1, x2)
    elif inf1 is not None and inf2 is not None:
        return cmp(inf1, inf2)
    elif inf1 is not None and real2 is not None:
        return inf1
    elif real1 is not None and inf2 is not None:
        return -inf2
    else:
        return None
Пример #32
0
def parse_for_chord (time, line):
  MAX = (gmpy.mpz (1) << 160) - 1
  RADIUS = gmpy.mpz (700)
  CX, CY = [gmpy.mpz (1000), gmpy.mpz (1000)]
  node_id = line.split(' ')[2]
  if ('node_attr2' in line):
    id = gmpy.mpz (line.rpartition(':')[2], 16)
    angle = gmpy.mpf (math.pi) * id / MAX
    x, y = CX + RADIUS * math.cos (angle), CY + RADIUS * math.sin(angle)
    add_event (time, '%ldns position %s %f %f 0 0 0 0\n' % (time, node_id, x, y))
    add_event (time, '%ldns state %s +chordRing\n' % (time, node_id))
Пример #33
0
    def zeros(self):
        order = len(self.coeff) - 1
        coeff = self.coeff[:]
        roots = []
        for i in range(order):
            r = self._laguerre(
                coeff, Complex(mpf(0, self.precision), mpf(0, self.precision)))
            roots.append(r)
            if i == order - 1: break
            rem = coeff[-1]
            for j in range(len(coeff) - 2, -1, -1):
                temp = coeff[j]
                coeff[j] = rem
                rem = temp + rem * r
            coeff = coeff[:-1]


##          for i in range(order):
##              roots[i] = self._laguerre(self.coeff, roots[i])
        return roots
Пример #34
0
def parse_for_chord(time, line):
    MAX = (gmpy.mpz(1) << 160) - 1
    RADIUS = gmpy.mpz(700)
    CX, CY = [gmpy.mpz(1000), gmpy.mpz(1000)]
    node_id = line.split(' ')[2]
    if ('node_attr2' in line):
        id = gmpy.mpz(line.rpartition(':')[2], 16)
        angle = gmpy.mpf(math.pi) * id / MAX
        x, y = CX + RADIUS * math.cos(angle), CY + RADIUS * math.sin(angle)
        add_event(time,
                  '%ldns position %s %f %f 0 0 0 0\n' % (time, node_id, x, y))
        add_event(time, '%ldns state %s +chordRing\n' % (time, node_id))
Пример #35
0
def pi_gmpy(prec):
    """gmpy.mpf"""
    set_minprec(prec)
    lasts, t, s, n, na, d, da = mpf(0), mpf(3), mpf(3), mpf(1), mpf(0), mpf(
        0), mpf(24)
    while s != lasts:
        lasts = s
        n, na = n + na, na + 8
        d, da = d + da, da + 32
        t = (t * n) / d
        s += t
    return s
Пример #36
0
def HG_split_diode_coefficient_analytical(n1,n2):
    """ Using an analytical equation to compute beat coefficients
    betwween mode n1 and n2 on a split photo detector. Uses arbitrary
    precision (from gmpy) because otherwise errors get very large
    for n1,n2>30. This is for comparison with the numerical method
    HG_split_diode_coefficient_numerical only. """
    import gmpy
    
    temp=gmpy.mpq(0.0)
    for l in np.arange(0,n1/2+1):
        for k in np.arange(0,(n2-1)/2+1):
            temp +=  gmpy.mpq(pow((-1.0/4.0),l+k)*gmpy.mpz(factorial((n2+n1-1)/2-l-k))/gmpy.mpz((factorial(l)*factorial(k)*factorial(n1-2*l)*factorial(n2-2*k))))

    c_n1n2=gmpy.mpq(temp*gmpy.mpq(math.sqrt(2.0**(n1+n2)*gmpy.mpz(factorial(n1)*factorial(n2))/np.pi)))
    return float(gmpy.mpf(c_n1n2))
Пример #37
0
def plot_list(bispectrums=bispectrums, comparison = 'elaine.512'):
    bispectrum_diff = {}
    for elem in bispectrums:
        diff = LA.norm(bispectrums[elem]-bispectrums[comparison])
        # we remove nan results
        if not np.isnan(diff):
            bispectrum_diff[elem] = diff
    
    sorted_diff = sorted(bispectrum_diff.items(), key=operator.itemgetter(1))
    
    plt.rcParams['figure.figsize'] = (20.0, 100.0)
    for i in range(len(sorted_diff)):
        plt.subplot(len(sorted_diff),1,i+1)
        plt.imshow(plt.imread(folder + sorted_diff[i][0] + '.png'),cmap=cm.binary_r)
        plt.annotate(str(gmpy.mpf(sorted_diff[i][1]).digits(10, 0, -1, 1)),xy = (120.,0.),xycoords='axes points')
    plt.rcParams = plt.rcParamsDefault
Пример #38
0
def main():
    if len(sys.argv) < 2:
        print 'Please provide input file'
        print 'Usage: %s inputfile [outputfile]' % sys.argv[0]
        return
    timestart = datetime.datetime.now()

    try:
        inputFile = open(sys.argv[1])
    except:
        print 'Failed to read input file %s' % sys.argv[1]
        return
    try:
        outputFile = open(sys.argv[2], 'w') if len(sys.argv) >= 3 else None
    except:
        print 'Failed to create output file %s' % sys.argv[2]
        return

    testCases = int(inputFile.readline().strip())

    print '-----------------'
    print 'Test cases: %d ' % testCases
    print 'No output file' if len(
        sys.argv) < 3 else 'Writing to %s' % sys.argv[2]
    print '-----------------'

    for testCaseNumber in range(1, testCases + 1):

        c, f, x = map(lambda x: mpf(x),
                      map(float,
                          inputFile.readline().strip().split()))

        string = 'Case #%d: %.7f' % (testCaseNumber, solve(c, f, x))

        print string
        if outputFile:
            outputFile.write(string + '\n')

    print '-----------------'
    print 'Written to %s' % sys.argv[2] if outputFile else 'No output file'
    print 'Elapsed time: %s' % (datetime.datetime.now() - timestart)
    print '-----------------'

    inputFile.close()
    if outputFile:
        outputFile.close()
Пример #39
0
def plot_list(bispectrums=bispectrums, comparison='elaine.512'):
    bispectrum_diff = {}
    for elem in bispectrums:
        diff = LA.norm(bispectrums[elem] - bispectrums[comparison])
        # we remove nan results
        if not np.isnan(diff):
            bispectrum_diff[elem] = diff

    sorted_diff = sorted(bispectrum_diff.items(), key=operator.itemgetter(1))

    plt.rcParams['figure.figsize'] = (20.0, 100.0)
    for i in range(len(sorted_diff)):
        plt.subplot(len(sorted_diff), 1, i + 1)
        plt.imshow(plt.imread(folder + sorted_diff[i][0] + '.png'),
                   cmap=cm.binary_r)
        plt.annotate(str(gmpy.mpf(sorted_diff[i][1]).digits(10, 0, -1, 1)),
                     xy=(120., 0.),
                     xycoords='axes points')
    plt.rcParams = plt.rcParamsDefault
Пример #40
0
    def apply(self, c, G, h, evaluation):
        "LinearProgramming[c_, G_, h_]"

        (c, G, h), subs = to_sage((c, G, h), evaluation)
        n = len(c)
        c = vector(c)
        G = matrix([[-item for item in row] for row in G] + [unit_vector(k, n, -1) for k in range(n)])
        h = vector([-item for item in h] + [0] * n)
        result = linear_program(c, G, h)
        status = result["status"]
        if status == "dual infeasible":
            evaluation.message("LinearProgramming", "lpsub")
            return Expression("List", *([Symbol("Indeterminate")] * n))
        elif status == "primal infeasible":
            return evaluation.message("LinearProgramming", "lpsnf")
        # print result
        x = result["x"]
        x = [round(value, mpf("0.000001")) for value in x]  # round result to 6 digits after comma
        return from_sage(x, subs)
Пример #41
0
 def __init__(self, model, precision=0):
     self.precision = precision
     self.order = model.order
     self.delta_t = model.delta_t
     if model.coeff.typecode() == N.Complex64:
         self.coeff = [
             N.Complex(mpf(x.real, precision), mpf(x.imag, precision))
             for x in model.coeff
         ]
     else:
         self.coeff = [mpf(x, precision) for x in model.coeff]
     self.sigsq = mpf(model.sigsq, precision)
     self.sigma = mpf(model.sigma, precision)
     self.variance = mpf(model.variance, precision)
     self._poles = None
Пример #42
0
def intersect_gmpy (A,B,C,D):
    acd = ccw(A,C,D)
    bcd = ccw(B,C,D)
    abc = ccw(A,B,C)
    abd = ccw(A,B,D)

    #literal edge cases, when one of our points lies on the opposite line
    if (acd == 0 and betweenpts(A,C,D)) or (bcd == 0 and betweenpts(B,C,D))\
    or (abc == 0 and betweenpts(A,B,C)) or (abd == 0 and betweenpts(A,B,D))\
    or (isgtzero (acd) != isgtzero (bcd) and isgtzero (abc) != isgtzero (abd)) :

        denom = gmpy.mpf(((D.y-C.y)*(B.x-A.x))- ((D.x-C.x)*(B.y-A.y)))
        uanumerator = gmpy.mpf(((D.x-C.x)*(A.y-C.y))-((D.y-C.y)*(A.x-C.x)))
        ubnumerator = gmpy.mpf(((B.x-A.x)*(A.y-C.y))-((B.y-A.y)*(A.x-C.x)))
        if denom == 0:
            # Lines are parallel, so return no
            return (0,0,0)
        else:
            ua = gmpy.mpf(uanumerator/denom)
            ub = gmpy.mpf(ubnumerator/denom)

            #if ua and ub are both between 0 and 1, then the intersection is in  both segments
            #NOTE: it does not matter which determinant we use for the equations below
            x = gmpy.mpf (A.x + (ua*(B.x-A.x)))
            y = gmpy.mpf (A.y + (ua*(B.y-A.y)))
            sign = 1

            #if the segment has the same y values (horizontal) then if going west it is negative
            #if the segment has different y values, going south is negative
            if (A.y==B.y and A.x>B.x) or (A.y>B.y):
                sign = sign * -1

            if min(A.x,B.x) <= x <= max(A.x,B.x) and\
              min(A.y,B.y) <= y <= max(A.y,B.y):
              return (x,y,sign)
            else:
              return (0,0,0)

    return (0,0,0)
Пример #43
0
 def to_string(self):
     X = self.val
     mantissa, e = self.mantissa_exponent()
     prec = int(X['_mpfr_prec'])
     exp = int(X['_mpfr_exp'])
     wordsize = 64
     special = -pow(2, wordsize - 1)
     sign = int(X['_mpfr_sign'])
     if exp == special + 2:
         return "NaN"
     if exp == special + 1:
         if sign < 0:
             return "-0"
         else:
             return "0"
     if exp == special + 3:
         if sign < 0:
             return "-inf"
         else:
             return "+inf"
     res = mpf(mantissa, prec)
     if e > 0: res *= pow(mpz(2), e)
     else: res /= pow(mpz(2), -e)
     return truncate_output(str(res))
    tot=sum(range(n), zero)
    stend=time.clock()
    return type(zero), stend-start, tot

def timedmul(n, one):
    start=time.clock()
    tot=one
    for i in range(n):
        tot*=(i+1)
    stend=time.clock()
    return type(one), stend-start, tot

def test(n=100*1000):
    print "Sum of %d items of various types:" % n
    for z in 0L, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum(n, z)
        print "    %5.3f %.0f %s" % (tim, float(tot), tip)
    print "Sum of %d items of various types w/2.3 sum builtin:" % n
    for z in 0L, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum1(n, z)
        print "    %5.3f %.0f %s" % (tim, float(tot), tip)
    print "Mul of %d items of various types:" % (n//5)
    for z in 1L, 1.0, gmpy.mpz(1), gmpy.mpf(1):
        tip, tim, tot = timedmul(n//5, z)
        print "    %5.3f %s" % (tim, tip)


if __name__=='__main__':
    test()

Пример #45
0
 def pkl_to_mpf((digit_str, prec)):
     return mpf(digit_str, prec, 10)
Пример #46
0
 def test_numbers_are_immutable_in_present_version(self):
     one = mpf('1.0', 32)
     one_orig = one
     one += 1.0
     self.assert_(one == 2.0)
     self.assert_(one_orig == 1.0)
Пример #47
0
# partial unit test for gmpy/decimal interoperability
# note: broken in Python 2.4.0 due to a 2.4.0 bug, please update to 2.4.1
#       or better to allow decimal/most-anything-else interoperability!-)
# relies on Tim Peters' "doctest.py" test-driver

r'''
>>> filter(lambda x: not x.startswith('__'), dir(f))
['_copy', 'binary', 'ceil', 'digits', 'f2q', 'floor', 'getprec', 'getrprec', 'qdiv', 'reldiff', 'round', 'setprec', 'sign', 'sqrt', 'trunc']
>>>
'''
try: import decimal as _d
except ImportError: _d = None

import gmpy as _g, doctest, sys
__test__={}
f=_g.mpf('123.456')
q=_g.mpq('789123/1000')
z=_g.mpz('234')
if _d: d=_d.Decimal('12.34')

__test__['elemop']=\
r'''
>>> print _g.mpz(23) == _d.Decimal(23)
True
>>> print _g.mpz(d)
12
>>> print _g.mpq(d)
617/50
>>> print _g.mpf(d)
12.34
>>> print f+d
Пример #48
0
import gmpy
import numpy
from matplotlib import pyplot
import pickle
import math

N=1000

pi=gmpy.pi(N)

pi2=pi/2
pi2_minus = -pi2
pix2 = pi*2
pi_minus = -pi

mpone=gmpy.mpf(1,N)

eps=gmpy.mpf(2)**(-N)


def sin_taylor(x):
	x2 = x*x
	s=0
	i=2
	an = x
	sgn = 1
	while True:
		s = s + sgn*an
		an = an*x2/(i*(i+1))
		i += 2
		sgn = -sgn		
def test(n=100*1000):
    print "Sum of %d items of various types:" % n
    for z in 0L, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum(n, z)
        print "    %5.3f %.0f %s" % (tim, float(tot), tip)
Пример #50
0
def dquot(x0,fx0,h):
	x = x0+gmpy.mpf(h,N)
	f = ssin(x)
	return float((f-fx0)/h)
Пример #51
0
	def __init__(self, x=0, y=0):
		self.x = gmpy.mpf(x)
		self.y = gmpy.mpf(y)
Пример #52
0
#!/usr/bin/python

# Calculate digits of e
# Marcus Kazmierczak, [email protected]
# July 29th, 2004

# the formula
#  e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + ... 1/N!

# You should chop off the last five digits returned
# they aren't necessarily accurate



# precision library 
import gmpy

# how many digits (roughly)
N = 1000


gmpy.set_minprec(int(N*3.5+16))
e = gmpy.mpf('1.0')
    
for n in range(1,N+3):
    e = gmpy.fdigits(gmpy.mpf(e) + (gmpy.mpf('1.0') / gmpy.fac(n)))

print e
Пример #53
0
Support for numeric evaluation with arbitrary precision is just a proof-of-concept.
Precision is not "guarded" through the evaluation process. Only integer precision is supported.
However, things like 'N[Pi, 100]' should work as expected.
"""

from gmpy import mpz, mpf
import mpmath
from mpmath import mpi

from mathics.builtin.base import Builtin, Predefined
from mathics.core.numbers import dps, mpmath2gmpy
from mathics.core import numbers
from mathics.core.expression import Integer, Rational, Real, Complex, Atom, Expression, Number, Symbol

machine_precision = dps(mpf(53))

def get_precision(prec, evaluation):
    if prec.get_name() == 'MachinePrecision':
        return numbers.prec(machine_precision)
    elif isinstance(prec, (Integer, Rational, Real)):
        return numbers.prec(prec.value)
    else:
        evaluation.message('N', 'precbd', prec)
        return None

class N(Builtin):
    """
    <dl>
    <dt>'N[$expr$, $prec$]'
        <dd>evaluates $expr$ numerically with a precision of $prec$ digits.
Пример #54
0
# partial unit test for gmpy mpf functionality
# relies on Tim Peters' "doctest.py" test-driver

r'''
>>> filter(lambda x: not x.startswith('__'), dir(a))
['_copy', 'binary', 'ceil', 'digits', 'f2q', 'floor', 'getprec', 'getrprec', 'qdiv', 'reldiff', 'round', 'setprec', 'sign', 'sqrt', 'trunc']
>>>
'''
import warnings
warnings.filterwarnings('ignore', 'setprec')

import sys

import gmpy as _g, doctest, sys
__test__={}
a=_g.mpf('123.456')
b=_g.mpf('789.123')

__test__['elemop']=\
r'''
>>> str(a+b)
'912.579'
>>> str(a-b)
'-665.667'
>>> str(a*b)
'97421.969088'
>>> str(a/b)
'0.156447093799065544915'
>>> str(b+a)
'912.579'
>>> str(b-a)
Пример #55
0
from __future__ import absolute_import

import string
import math
import binascii
import six

import gmpy as gmpy

from Crypto.Cipher import AES
from six.moves import range

_gmpy_mpz_type = type(gmpy.mpz(0))
_gmpy_mpf_type = type(gmpy.mpf(0))


def new(K, radix):
    return FFXEncrypter(K, radix)


class Bottom(Exception):
    pass


class UnknownTypeException(Exception):
    pass


class InvalidRadixException(Exception):
    pass
Пример #56
0
 def testCreateWithHighPrecision(self):
     f = Float(1.0,128)
     self.assertEqual(128, f.getprec())
     self.assertEqual(f, gmpy.mpf(1.0,128))
Пример #57
0
Support for numeric evaluation with arbitrary precision is just a proof-of-concept.
Precision is not "guarded" through the evaluation process. Only integer precision is supported.
However, things like 'N[Pi, 100]' should work as expected.
"""

from gmpy import mpz, mpf
import mpmath
from mpmath import mpi

from mathics.builtin.base import Builtin, Predefined
from mathics.core.numbers import dps, mpmath2gmpy
from mathics.core import numbers
from mathics.core.expression import Integer, Rational, Real, Complex, Atom, Expression, Number, Symbol

machine_precision = dps(mpf(64))


def get_precision(prec, evaluation):
    if prec.get_name() == "MachinePrecision":
        return numbers.prec(machine_precision)
    elif isinstance(prec, (Integer, Rational, Real)):
        return numbers.prec(prec.value)
    else:
        evaluation.message("N", "precbd", prec)
        return None


class N(Builtin):
    """
    <dl>