예제 #1
0
def next111(strBound, precVar):
    if precVar == (23, 8):
        origValue = single(eval(strBound))
        strOrigValue = strFormatFromDecimalLib(origValue)
        if strOrigValue != strBound:  #bound is not exactly representable in double or single precision
            n, d = bigfloat.next_up(
                eval(strOrigValue),
                context=bigfloat.precision(24)).as_integer_ratio()
            newValue = single(n / float(d))
            if newValue > origValue:
                return strFormatFromDecimalLib(newValue)
            else:
                exit("Problem in conversion of bound:" + strBound)
        else:
            return strOrigValue
    elif precVar == (52, 11):
        origValue = Decimal(eval(strBound))
        strOrigValue = strFormatFromDecimalLib(origValue)
        if strOrigValue != strBound:  #bound is not exactly representable in double or single precision
            n, d = bigfloat.next_up(
                eval(strOrigValue),
                context=bigfloat.precision(53)).as_integer_ratio()
            newValue = eval("Decimal(" + str(n) + "/" + str(d) + ".0)")
            if newValue > origValue:
                return strFormatFromDecimalLib(newValue)
            else:
                exit("Problem in conversion of bound:" + strBound)
        else:
            return strOrigValue
    else:
        exit("Precision not recognized")
예제 #2
0
def getInfo(data, target, theta):
    afterSigmoid = sigmoid(data.dot(theta))

    firstList = [ ]
    for k in afterSigmoid:
        m = []
        for x in k:
            m.append(bigfloat.log(x,bigfloat.precision(precision)))
        firstList.append(m)

    secondList = [ ]
    for k in afterSigmoid:
        m = []
        for x in k:
            m.append(bigfloat.log( bigfloat.sub(1. , x) , bigfloat.precision(precision)))
        secondList.append(m)
    
    Ein = 0.
    m = []
    for x,y in zip(firstList, secondList):
        for a,b,t in zip(x,y,target):
            value = bigfloat.add( bigfloat.mul(t[0],a, bigfloat.precision(precision)) , bigfloat.mul( bigfloat.sub(1. ,t[0], bigfloat.precision(precision)) ,a, bigfloat.precision(precision)))
            m.append(value)
    for item in m:
        Ein = bigfloat.add(item, Ein, bigfloat.precision(precision))
    
    Ein = - Ein
    print(Ein)
    gradient = -data.T.dot(target-afterSigmoid)
    return (Ein, gradient)
예제 #3
0
def Evaluate(pk,cl,ck,s={}):
    #S is for debugging
    (pk0,x,y)=pk
    cl0=[]
    for (i,j) in cl:
        cl0.append(i)
    c0 = SomeWhatEvaluate((pk0,x), cl0, ck)
    z=[None]*(Params.bigo+1)
    for i in range(1,Params.bigo+1):
        k=bigfloat.mul(c0,y[i],bigfloat.precision((Params.kappa+Params.gamma)))
        z[i]=float(bigfloat.mod(k,2,bigfloat.precision((Params.prec))))
    if debug:
        su=0
        yo=0
        for i in range(1,Params.bigo+1):
            if s[i]==1:
                yo=bigfloat.add(yo,y[i],bigfloat.precision((Params.kappa+Params.gamma)))
                su=bigfloat.add(su,z[i],bigfloat.precision(Params.kappa+Params.gamma))
        print "Enc_sum%2=",bigfloat.mod(su,8,bigfloat.precision((Params.prec+Params.gamma)))
        q=bigfloat.div(c0,globsk,bigfloat.precision(Params.kappa+Params.gamma))
        print "(c0/sk)=",q
        q=bigfloat.mul(c0,yo,bigfloat.precision((Params.kappa+Params.gamma)))
        print "(c0*yo)=",q
        q=bigfloat.div(1,globsk,bigfloat.precision(Params.kappa+Params.gamma))
        print "(1/sk)=",q
        print "(yo)=",yo
        print "(c0*1/sk)=",bigfloat.mul(q,c0,bigfloat.precision((Params.prec+Params.gamma)))
        q=bigfloat.div(c0,globsk,bigfloat.precision((Params.prec+Params.gamma)))
        print "(c0/sk)=",q
    c = (c0,z)
    return c
예제 #4
0
    def GenLn2(self):
        with precision(128):
            ln2 = bigfloat.log(2.0)
            l = bin64(ln2).hex1int() & 0xffffffffe0000000
            ld = bin64(hex_to_double(l))
            print(".ln_lead = ", double_to_hex(ld), ld.hex())

        with precision(128):
            t = ln2 - ld
            tail = bin64(t)
            print(".ln_tail = ", double_to_hex(tail), tail.hex())
예제 #5
0
 def appendZVector(self, c0):
     y = self.yvector
     z=[None]*(Params.bigo+1)
     for i in range(1,Params.bigo+1):
         k=bigfloat.mul(c0,y[i],bigfloat.precision(Params.gamma+Params.kappa))
         z[i]=float(bigfloat.mod(k,2,bigfloat.precision(Params.prec)))
         # Sometimes mod goes wrong
         if z[i]>=2.0:
             z[i]=0
     c = (c0,z)
     return c
예제 #6
0
    def GenLn2(self):
        with precision(128):
            ln2 = bigfloat.log(2.0)
            h = -ln2 / self.table_size
            hint = bin64(h).hex1int() & 0xffffffffffff0000
            hd = bin64(hex_to_double(hint))
            print(".ln2by_tblsz_head = ", hd.hex())

        with precision(128):
            t = h - hd
            tail = bin64(t)
            print(".ln2by_tblsz_tail = ", tail.hex())
예제 #7
0
 def interval_bf_operation(self,
                           precision_of_result: int,
                           ad: bool = False):
     self.precision = precision_of_result
     child = self.child
     context_down = bf.precision(precision_of_result) + bf.RoundTowardNegative
     context_up = bf.precision(precision_of_result) + bf.RoundTowardPositive
     interval, deriv = self.unary_op([child.lower, child.upper], context_down, context_up)
     self.lower, self.upper = interval
     lower_deriv, upper_deriv = deriv
     if ad:
         child.ad_lower_children.append((lower_deriv, self))
         child.ad_upper_children.append((upper_deriv, self))
예제 #8
0
    def partition_functions_for_each_configuration(self):
        """
        Inversely solve the free energy to get partition function for :math:`j` th configuration by

        .. math::

           Z_{j}(T, V) = \exp \\bigg( -\\frac{ F_{j}(T, V) }{ k_B T } \\bigg).

        :return: A matrix, the partition function of each configuration of each volume.
        """
        try:
            import bigfloat
        except ImportError:
            raise ImportError(
                "Install ``bigfloat`` package to use {0} object!".format(
                    self.__class__.__name__))

        with bigfloat.precision(self.precision):
            return np.array([
                bigfloat.exp(d)
                for d in  # shape = (# of volumes for each configuration, 1)
                logsumexp(
                    -self.aligned_free_energies_for_each_configuration.T /
                    (K * self.temperature),
                    axis=1,
                    b=self.degeneracies)
            ])
예제 #9
0
        def sollya_gamma_fct(x, diff_order, prec):
            """ wrapper to use bigfloat implementation of exponential
                rather than sollya's implementation directly.
                This wrapper implements sollya's function API.

                :param x: numerical input value (may be an Interval)
                :param diff_order: differential order
                :param prec: numerical precision expected (min)
            """
            fct = None
            if diff_order == 0:
                fct = sollya_gamma
            elif diff_order == 1:
                fct = sollya_gamma_d0
            elif diff_order == 2:
                fct = sollya_gamma_d1
            else:
                raise NotImplementedError
            with bigfloat.precision(prec):
                if x.is_range():
                    lo = sollya.inf(x)
                    hi = sollya.sup(x)
                    return sollya.Interval(fct(lo), fct(hi))
                else:
                    return fct(x)
예제 #10
0
 def FLOAT(self, t):
     #t.value = float(t.value)
     #t.value = np.float128(t.value)
     t.value = bf.BigFloat(t.value, bf.precision(128))
     #t.value = t.value
     #print("value -> ", t.value)
     return t
예제 #11
0
파일: ASTtypes.py 프로젝트: sljiaa/Satire
    def get_noise(obj):
        if float(obj.token.value).is_integer and float(
                obj.token.value) == obj.token.value:
            return 0

        if bf.sub(bf.BigFloat(obj.token.value, bf.precision(113)),
                  bf.BigFloat(obj.token.value, bf.precision(50)),
                  bf.precision(1024)) == 0:
            return 0
        v = math.log(abs(obj.token.value), 2)
        if (v - math.floor(v) != 0.0):
            if (obj.token.value <= 0):
                return -pow(2, math.floor(v))
            else:
                return pow(2, math.floor(v))
        return 0.0  #obj.token.value
예제 #12
0
def run_benchmark(log_error_bound: int,
                  benchmark: Benchmark,
                  configuration_increment: Optional[Callable] = None,
                  use_ad: bool = False):
    exact_program, variables = benchmark.benchmark(), benchmark.variables
    init_prec = 50

    context = bf.RoundTowardZero + bf.precision(100000)
    assert log_error_bound < 0, "Log error bound should be negative!"
    error_bound = bf.BigFloat(f'0.{"0"*(-log_error_bound-1)}1', context)
    [var.sample() for var in variables]
    if use_ad:
        params = [
            exact_program, error_bound,
            [init_prec] * exact_program.subtree_size()
        ]
        time, (num_refinements,
               precision_configuration) = time_wrap(evaluate_using_derivatives,
                                                    params)
    else:
        params = [
            exact_program, error_bound, configuration_increment, True,
            init_prec
        ]
        time, (num_refinements,
               precision_configuration) = time_wrap(evaluate, params)
    data = {
        "time": time.total_seconds(),
        "num_refinements": num_refinements,
        "log_error_bound": float(log_error_bound),
        "last_prec_config": precision_configuration,
    }
    return data
예제 #13
0
 def _compute_grad(self, children: List) -> bf.BigFloat:
     context = bf.precision(self.grad_precision) + bf.RoundAwayFromZero
     grad = 0
     for (w1, w2), var in children:
         lower, upper = var.grad()
         grad_term = bf.add(bf.mul(w1, lower, context), bf.mul(w2, upper, context), context)
         grad = bf.add(grad_term, grad, context)
     return grad
예제 #14
0
def reprocessKey(pk):
    (pk0,x0,y0)=pk
    y={}
    for i in range(1,Params.bigo+1):
        k = bigfloat.BigFloat(y0[i],bigfloat.precision(Params.kappa))
        y[i] = k
    pk=(pk0,x0,y)
    return pk  
예제 #15
0
def sigmoid(s):
    y = []
    for k in s:
        z=[]
        for l in k:
            z.append( bigfloat.div( 1. , bigfloat.add(1,bigfloat.exp(-l,bigfloat.precision(precision)))))
        y.append(z)
    return np.array(y)
예제 #16
0
 def sigmoidx(x, derivative):
     # the function
     s = 1 / (1 + bfloat.exp(-x / 20, bfloat.precision(30)))
     # if derivative is true, the output is the derivative
     if derivative == True:
         return (s + s * (1 - s))
     else:
         return s
예제 #17
0
    def interval_bf_operation(self,
                              precision_of_result: int,
                              ad: bool = False):
        self.precision = precision_of_result
        left, right = self.children
        context_down = bf.precision(precision_of_result) + bf.RoundTowardNegative
        context_up = bf.precision(precision_of_result) + bf.RoundTowardPositive
        self.lower = bf.sub(left.lower, right.upper, context_down)
        self.upper = bf.sub(left.upper, right.lower, context_up)

        if ad:
            left, right = self.children

            left.ad_lower_children.append(((1,  0), self))
            right.ad_lower_children.append(((0, -1), self))

            left.ad_upper_children.append(((0, 1), self))
            right.ad_upper_children.append(((-1, 0), self))
예제 #18
0
    def multiply(left_lower: BigFloat,
                 left_upper: BigFloat,
                 right_lower: BigFloat,
                 right_upper: BigFloat,
                 precision_of_result: int):
        context_down = bf.precision(precision_of_result) + bf.RoundTowardNegative
        context_up = bf.precision(precision_of_result) + bf.RoundTowardPositive

        # Note: inefficient to compute all pairs, Kaucher multiplication in future?
        ll_down = bf.mul(left_lower, right_lower, context_down), (left_lower, 0), (right_lower, 0)
        lu_down = bf.mul(left_lower, right_upper, context_down), (left_lower, 0), (right_upper, 1)
        ul_down = bf.mul(left_upper, right_lower, context_down), (left_upper, 1), (right_lower, 0)
        uu_down = bf.mul(left_upper, right_upper, context_down), (left_upper, 1), (right_upper, 1)

        ll_up = bf.mul(left_lower, right_lower, context_up), (left_lower, 0), (right_lower, 0)
        lu_up = bf.mul(left_lower, right_upper, context_up), (left_lower, 0), (right_upper, 1)
        ul_up = bf.mul(left_upper, right_lower, context_up), (left_upper, 1), (right_lower, 0)
        uu_up = bf.mul(left_upper, right_upper, context_up), (left_upper, 1), (right_upper, 1)

        (lower_product, (ll, ll_ind), (lr, lr_ind)) = min([ll_down, lu_down, ul_down, uu_down], key=lambda x: x[0])
        (upper_product, (ul, ul_ind), (ur, ur_ind)) = max([ll_up, lu_up, ul_up, uu_up], key=lambda x: x[0])

        # Assign derivative weights based on partial derivatives in chain rule
        llw, lrw, ulw, urw = [[0., 0.], [0., 0.], [0., 0.], [0., 0.]]
        if ll_ind == 0:
            llw[0] = float(lr)
        else:
            ulw[0] = float(lr)

        if lr_ind == 0:
            lrw[0] = float(ll)
        else:
            urw[0] = float(ll)

        if ul_ind == 0:
            llw[1] = float(ur)
        else:
            ulw[1] = float(ur)

        if ur_ind == 0:
            lrw[1] = float(ul)
        else:
            urw[1] = float(ul)
        return lower_product, upper_product, llw, lrw, ulw, urw
예제 #19
0
def SomeWhatDecrypt(sk,c):
    t = sk/2
    if debug:
        x = int(bigfloat.div(c,sk,bigfloat.precision(1000)))
        y = c/sk
        print "SomeWhatDecrypt:x:",x
        print "SomeWhatDecrypt:y:",y
        print "SomeWhatDecrypt:c%sk:",c%sk
        print "SomeWhatDecrypt:c-x*sk:",c-x*sk
    return (c-(c+t)/sk)%2
예제 #20
0
def logn2(n, p):
    """Best p-bit lower and upper bounds for log(2)/log(n), as Fractions."""
    with precision(p):
        extra = 10
        while True:
            with precision(p + extra):
                # use extra precision for intermediate step
                log2upper = log2(n, RoundTowardPositive)
                log2lower = log2(n, RoundTowardNegative)

            lower = div(1, log2upper, RoundTowardNegative)
            upper = div(1, log2lower, RoundTowardPositive)

            # if lower and upper are adjacent (or equal) we're done
            if next_up(lower) == upper:
                return (Fraction(*lower.as_integer_ratio()),
                        Fraction(*upper.as_integer_ratio()))

            # otherwise, increase the precision and try again
            extra += 10
예제 #21
0
    def binary_to_range(self, point: str, precision) -> BigFloat:
        """ Bring a point from [0, 1] to a given range. """
        point = point[:precision + 2]
        interval_width = self.var_upper - self.var_lower
        bitwidth = len(point) - 2
        full_prec_context = bf.precision(bitwidth) + bf.RoundTowardNegative

        # Map to [0, 1]
        value = bf.mul(int(point, 2), bf.exp2(-bitwidth, full_prec_context), full_prec_context)
        rescaled = bf.add(bf.mul(value, interval_width, full_prec_context), self.var_lower, full_prec_context)
        return rescaled
예제 #22
0
    def GenTable(self):
        #newsize = self.table_size +  1
        newsize = self.table_size << 1
        for j in range(0, newsize):  # 0 to 256
            with precision(256):
                f = bigfloat.log(1 + j / newsize)
                f_leadint = bin64(f).hex1int() & 0xfffffffff0000000
                f_tail = f - hex_to_double(f_leadint)

            #print("%x"%f_leadint, double_to_hex(float(f_tail)))
            print("{", "0x%x, %s" % (f_leadint, double_to_hex(f_tail)), "},")
예제 #23
0
def logn2(n, p):
    """Best p-bit lower and upper bounds for log(2)/log(n), as Fractions."""
    with precision(p):
        extra = 10
        while True:
            with precision(p+extra):
                # use extra precision for intermediate step
                log2upper = log2(n, RoundTowardPositive)
                log2lower = log2(n, RoundTowardNegative)

            lower = div(1, log2upper, RoundTowardNegative)
            upper = div(1, log2lower, RoundTowardPositive)

            # if lower and upper are adjacent (or equal) we're done
            if next_up(lower) == upper:
                return (Fraction(*lower.as_integer_ratio()),
                        Fraction(*upper.as_integer_ratio()))

            # otherwise, increase the precision and try again
            extra += 10
예제 #24
0
파일: pb80.py 프로젝트: oursinblanc/Euler
def main():
    start = time.perf_counter()
    somme = 0

    for i in range(1, 101):
        rac = bigfloat.sqrt(i, bigfloat.precision(385))
        if rac != int(rac):
            s = partie_decimale(rac)[:100]
            somme += sumdigits(int(s))

    print(somme)
    print('temps d execution', time.perf_counter() - start, 'sec')
예제 #25
0
 def GenTable(self):
     for i in range(0, self.table_size):
         idx = float(i) / self.table_size
         h1 = 0.0
         with precision(200):
             h1 = bigfloat.pow(2.0, idx)
         fm, fh, fl = split_double(h1)
         #print("{", fh.hex(), ", ", fl.hex(), "},\n", endl='')
         print("{", double_to_hex(fm), ", ", double_to_hex(fh), ", ",
               double_to_hex(fl), "},")
         if i % 16 == 0:
             print("// i = %d" % i)
예제 #26
0
    def mk_bfc(self, x, y):

        from bigfloat import BigFloat, precision
        from mbrat.util import Arguments

        with precision(self.prec):
            bf_x = BigFloat.exact(x)
            bf_y = BigFloat.exact(y)

        return Arguments(
            {'real': bf_x, 'imag': bf_y},
            string="bfc(real='{0}', imag='{1}')".format(bf_x, bf_y) )
예제 #27
0
def Decrypt(sk,c,calcZ=True,sk1=1):
    #sk1 is for debugging purpose
    su=0
    if calcZ:
        (c0,z) = c
        for i in range(1,Params.bigo+1):
            if sk[i]!=0:
                su=bigfloat.add(su,z[i],bigfloat.precision(Params.prec))
    else:
        c0 = c
        if Keys.PK==None:
            print "Error: Z vector must be provided when public key not available"
            exit()
        y = Keys.PK[2]
        for i in range(1,Params.bigo+1):
            if sk[i]!=0:
                z = bigfloat.mul(c0,y[i],bigfloat.precision(Params.kappa))
                z = float(bigfloat.mod(z,2,bigfloat.precision(Params.prec)))
                su=bigfloat.add(su,z,bigfloat.precision(Params.prec))
    su=int(bigfloat.round(su))
    m = (c0-su) % 2
    return m
예제 #28
0
    def invert(lower: BigFloat, upper: BigFloat, precision_of_result: int) -> ExactRealProgram:
        context_down = bf.precision(precision_of_result) + bf.RoundTowardNegative
        context_up = bf.precision(precision_of_result) + bf.RoundTowardPositive

        # interval doesn't contain zero then invert and flip [1 / y2, 1 / y1]
        if (lower > 0 and upper > 0) or (lower < 0 and upper < 0):
            inv_lower = bf.div(1, upper, context_down)
            inv_upper = bf.div(1, lower, context_up)
            lw = [0, -float(inv_upper)**2]
            uw = [-float(inv_lower)**2, 0]

        # [lower, 0] -> [-infty, 1 / y1]
        elif lower < 0 and upper == 0:
            inv_lower = BigFloat('-inf')
            inv_upper = bf.div(1, lower, context_up)
            lw = [0, float('nan')]
            uw = [-float(inv_lower)**2, 0]

        # [0, upper] -> [1 / y2, infty]
        elif lower == 0 and upper > 0:
            inv_lower = bf.div(1, upper, context_down)
            inv_upper = BigFloat('inf')
            lw = [0, -float(inv_upper)**2]
            uw = [float('nan'), 0]

        # If the interval includes 0 just give up and return [-infty, infty]
        # Note: an alternative is to split up intervals, but that's too tricky for now
        elif lower < 0 < upper:
            inv_lower = BigFloat('-inf')
            inv_upper = BigFloat('inf')
            lw = [0, float('nan')]
            uw = [float('nan'), 0]

        # Interval is probably such that lower is greater than upper
        else:
            raise ValueError("Input interval is invalid for division")

        return inv_lower, inv_upper, lw, uw
예제 #29
0
def EvaluateVector(pk,cl,ck,calcZ=True):
    (pk0,x0,y)=pk
    r=[]
    if calcZ:
        cl0=[]
        for (i,j) in cl:
            cl0.append(i)
    else:
        cl0=cl
    
    ck.setReductionVector(x0)  #This is added to Trees constructor
    r0 = ck.eval(cl0)
    if calcZ:
        for c0 in r0:
            z=[None]*(Params.bigo+1)
            for i in range(1,Params.bigo+1):
                k=bigfloat.mul(c0,y[i],bigfloat.precision(Params.kappa))
                z[i]=float(bigfloat.mod(k,2,bigfloat.precision(Params.prec)))
            c = (c0,z)
            r.append(c)
    else:
        r=r0
    return r
예제 #30
0
def transform_brute(s, l):
    with precision(100):
        ret = [BigFloat(0) for x in xrange(1 + s * (len(l)-1))]
        for i, v in enumerate(l):
            if i == 0:
                continue

            def rec(sum_, c):
                if i == c:
                    ret[sum_] += BigFloat(v)/(BigFloat(s)**i)
                else:
                    for x in xrange(1, s+1):
                        rec(sum_+x, c+1)
            rec(0, 0)
        return [x/sum(ret) for x in ret]
예제 #31
0
파일: parse_data.py 프로젝트: j3ny/Analysis
def get_boltzmann_distribution(energy_by_arm):
    R = 8.3144621  # gas constant
    T = 293.15  # room temperature
    factor = 4184.0  # joules_per_kcal
    boltzmann_distribution = []
    for dG in energy_by_arm:
        ps = []
        total = bigfloat.BigFloat(0)
        for energy in dG:
            p = bigfloat.exp((-energy*factor)/(R*T), bigfloat.precision(1000))
            ps.append(p)
            total = bigfloat.add(total, p)
        normal_ps = []
        for p in ps:
            normal_ps.append(float(bigfloat.div(p,total)))
        boltzmann_distribution.append(numpy.array(normal_ps))
    return boltzmann_distribution
예제 #32
0
def ExactIntegrationOfSinusKernel(t, a=None, b=None):
    with bigfloat.precision(300):
        if a == None and b == None:
            return 0.5 * math.pi * math.sqrt(t) * (mpmath.angerj(0.5, t) -
                                                   mpmath.angerj(-0.5, t))
        if a == None and b != None:
            a = t
        elif b == None:
            b = 0.
        mpmath.mp.pretty = True
        pi = mpmath.mp.pi
        pi = +pi
        fcos = mpmath.fresnelc
        fsin = mpmath.fresnels

        arg_a = mpmath.sqrt(2 * (t - a) / mpmath.mp.pi)
        arg_b = mpmath.sqrt(2 * (t - b) / mpmath.mp.pi)
        return mpmath.sqrt(2 * mpmath.mp.pi) * (
            (fsin(arg_b) - fsin(arg_a)) * mpmath.cos(t) +
            (fcos(arg_a) - fcos(arg_b)) * mpmath.sin(t))
예제 #33
0
def transform(s, l):
    with precision(100):
        ret = [BigFloat(0) for x in xrange(1 + s * (len(l)-1))]
        prev = [1]
        for i, v in enumerate(l):
            if i > 0:
                f = BigFloat(1) / (BigFloat(s) ** i)
                new = [BigFloat(0) for x in xrange(1 + s * i)]
                for faceval in xrange(1, s+1):
                    for idx, val in enumerate(prev):
                        new[idx+faceval] += val
                if v > 0:
                    for idx, val in enumerate(new):
                        ret[idx] += val * v * f
                prev = new
        # while ret[-1] == 0:
        #     ret.pop()
        print("s = ", s, " ; ret = ", ["%f" % x for x in ret])
        sys.stdout.flush()
        return [x/sum(ret) for x in ret]
예제 #34
0
    def get_free_energies(self):
        """
        Give the free energy by

        .. math::

           F_{\\text{all configs}}(T, V) = - k_B T \ln Z_{\\text{all configs}}(T, V).

        :return: The free energy on the temperature-volume grid.
        """
        try:
            import bigfloat
        except ImportError:
            raise ImportError(
                "Install ``bigfloat`` package to use {0} object!".format(
                    self.__class__.__name__))

        with bigfloat.precision(self.precision):
            log_z = np.array([bigfloat.log(d) for d in self.total],
                             dtype=float)
        return -K * self.temperature * log_z
예제 #35
0
    def _static_part(self) -> Vector:
        """
        Calculate the static contribution to the partition function.

        :return: The static contribution on the temperature-volume grid.
        """
        try:
            import bigfloat
        except ImportError:
            raise ImportError(
                "You need to install ``bigfloat`` package to use {0} object!".
                format(self.__class__.__name__))

        with bigfloat.precision(self.precision):
            return np.array([
                bigfloat.exp(d)
                for d in  # shape = (# of volumes for each configuration, 1)
                logsumexp(-self.static_energies / (K * self.temperature),
                          axis=1,
                          b=self.degeneracies)
            ])
예제 #36
0
def calc_variance_brute(x12):
    s = 20
    with precision(100):
        s_sq = [0, 0, 0]
        for i, v in enumerate(x12):
            if i > 0:
                f = BigFloat(1) / (BigFloat(s) ** i)
                print("i = ", i)

                def rec(s_sq, sum_, c):
                    if (c == i):
                        s_sq[0] += f * v * sum_ * sum_
                        s_sq[1] += f * v * sum_
                        s_sq[2] += f * v
                    else:
                        for x in xrange(1, 21):
                            rec(s_sq, sum_+x, c+1)
                rec(s_sq, 0, 0)
        print("s_sq = ", s_sq)
        return (BigFloat(s_sq[0])/BigFloat(s_sq[2]) -
                ((BigFloat(s_sq[1])/BigFloat(s_sq[2]))**2))
예제 #37
0
def calc_variance(x12):
    from bigfloat import precision, BigFloat
    num_faces = 20
    with precision(100):
        n = 0
        s = 0
        s_sq = BigFloat(0)
        this_base_n = BigFloat(1)
        base_s_sq = sum([x*x for x in xrange(1, 20+1)])
        base_s = sum([x for x in xrange(1, 20+1)])
        base_var = BigFloat(base_s_sq)/20 - BigFloat(base_s * base_s)/20/20
        for i, v in enumerate(x12):
            f = BigFloat(1) / (BigFloat(num_faces) ** i)
            n += f * this_base_n * v
            s += f * ((this_base_n * v * i * (1+20))*0.5)
            var = base_var * i
            var_less = var + BigFloat(base_s * base_s * i * i)/20/20
            sq = var_less * this_base_n
            s_sq += f * sq * v
            this_base_n *= 20
        return ((BigFloat(s_sq) / BigFloat(n)) -
                ((BigFloat(s)/BigFloat(n)) ** 2))
예제 #38
0
def permutation_collision_prob_bigfloat(n,
                                        m,
                                        w_in,
                                        w_out,
                                        precision=100,
                                        debug=False):
    '''
    Define the set of matrices A_set with dimensions (m x n) with m <= n, exactly one 1 in each row,
    and zero or one 1's in each column.  Consider sampling a matrix A uniformly at random from A_set.

    Inputs:
    - n: int, columns in A
    - m: int, rows in A
    - w_in: int, hamming weight of a vector x which we will multiply with A
    - w_out: int, we're interested in whether the vector Ax has hamming weight w_out

    Outputs:
    - prob: BigFloat, the probability that Ax has hamming weight w_out for any vector x with hamming weight w_in
    '''
    assert (m <= n)
    assert (w_in <= n)
    assert (w_out >= m - (n - w_in))
    assert (w_out <= w_in and w_out <= m)
    with bf.precision(precision):
        #the number of matrices in A_set such that Ax has hamming weight w_out for any x with hamming weight w_in
        prob = bigFloat_nCr(w_in, w_out) * bigFloat_nCr(n - w_in, m - w_out)
        #divide by the number of matrices in A_set
        prob /= bigFloat_nCr(n, m)
        if debug:
            A_set_size = bigFloat_nCr(n, m)
            check_A_set_size = 0
            for enum_w_out in range(max(0, m - (n - w_in)), min(w_in, m) + 1):
                check_A_set_size += bigFloat_nCr(
                    w_in, enum_w_out) * bigFloat_nCr(n - w_in, m - enum_w_out)


#            assert(np.abs(check_A_set_size - A_set_size) < .00001), (check_A_set_size, A_set_size)
        return prob
예제 #39
0
    def get_free_energies(self):
        """
        The free energy calculated from the partition function :math:`Z_{\\text{all configs}}(T, V)` by

        .. math::

           F_{\\text{all configs}}(T, V) = - k_B T \ln Z_{\\text{all configs}}(T, V).

        :return: The free energy on a temperature-volume grid.
        """
        try:
            import bigfloat
        except ImportError:
            raise ImportError(
                "Install ``bigfloat`` package to use {0} object!".format(
                    self.__class__.__name__))

        with bigfloat.precision(self.precision):
            log_z = np.array([
                bigfloat.log(d)
                for d in self.partition_functions_for_each_configuration
            ],
                             dtype=float)
        return -K * self.temperature * log_z
예제 #40
0
def Encrypt(pk,m,calcZ=True,s=None):
    #s is the secret key to be used for debugging purposes
    (pk0,x,y)=pk
    c0 = SomeWhatEncrypt((pk0,x), m)
    if calcZ:
        z=[None]*(Params.bigo+1)
        for i in range(1,Params.bigo+1):
            k=bigfloat.mul(c0,y[i],bigfloat.precision((Params.kappa+Params.gamma)))
            z[i]=float(bigfloat.mod(k,2.0,bigfloat.precision(Params.prec)))
            if z[i]>=2.0:
                z[i]=0
        c = (c0,z)
    else:
        c = c0
    if debug:
        su=0
        for i in range(1,Params.bigo+1):
            if s and s[i]==1:
                su=bigfloat.add(su,z[i],bigfloat.precision(Params.kappa+Params.gamma))
        print "Enc_sum%2=",bigfloat.mod(su,8,bigfloat.precision((Params.prec+Params.gamma)))
        q=bigfloat.div(c0,globsk,bigfloat.precision(Params.kappa+Params.gamma))
        print "(Enc_c/sk)%2=",bigfloat.mod(q,8,bigfloat.precision((Params.prec+Params.gamma)))
        print "c0=",c0
    return c
예제 #41
0
def KeyGen(Lambda):
    global globsk #For debugginh
    (sk0,pk0)=SomeWhatKeyGen(Lambda)
    globsk = sk0  #For debugging
    #Params.kappa = int(Params.gamma * Params.eta / Params.rho1)
    
    '''Tweak to approximate to nearest integer'''
    t=sk0/2+1
    xp=int((2**Params.kappa+t)/sk0) # Approximating to nearest integer
    S = []
    lenS=0
    while lenS!=Params.theta:
        i=random.randrange(1,Params.bigo)
        if i not in S:
            S.append(i)
            lenS+=1
    s={}
    for i in range(1,Params.bigo+1):
        if i in S:
            s[i]=1
        else:
            s[i]=0
    
    n = 2**(Params.kappa)      
    m = 2**(Params.kappa+1)
    u = {}
    approx = xp/Params.theta
    var = approx/Params.theta
    for i in range(1,Params.bigo+1):
        u[i]=random.randrange(0,m)
    su=0
    for i in S[:-1]:
        x =random.randrange(approx-var,approx+var)
        u[i]=x
        su+=u[i]
    i=S[-1]
    u[i]=xp-su
    
    y={}
    for i in range(1,Params.bigo+1):
        y[i]=bigfloat.div(u[i],n,bigfloat.precision((Params.kappa+Params.gamma)))
    #DEBUG
    if debug:
        su = 0
        su2=0
        for i in S:
            su2+=u[i]
            su=bigfloat.add(su,y[i],bigfloat.precision(Params.kappa+Params.gamma))
            inv = bigfloat.mul(n,y[i],bigfloat.precision(Params.kappa+Params.gamma))
            print u[i]
            print inv
        print "sumxp=",su2
        print "sumf=",su
        print "xp=", xp
        print "xp/n=", bigfloat.div(xp,n,bigfloat.precision(Params.kappa+Params.gamma))
        print "m=",m
        print Params.theta
        print Params.bigo
        print S
        print s
    #END DEBUG
    (pk1,x)=pk0
    pk = (pk1,x,y)
    return (s,pk)
예제 #42
0
# Deal with overflow in exp using numpy
import bigfloat
bigfloat.exp(5000,bigfloat.precision(100))
# -&gt; BigFloat.exact('2.9676283840236670689662968052896e+2171', precision=100)
예제 #43
0
파일: pi3.py 프로젝트: maurolacy/Babel
#!/usr/bin/python

from bigfloat import const_pi, precision
from string import translate, maketrans
print translate(str(const_pi(precision(5482))), maketrans('0123456789', '.Hdlro lwe'))
예제 #44
0
#!/usr/bin/env python

"""
Analyze the relationships between digits in pi.
"""

import bigfloat
from bigfloat import precision
import numpy
from scipy import stats

str_pi = str(bigfloat.atan2(+0.0, -0.0, precision(100000)))

# remove the "3." at the beginning of pi
pi = list(str_pi)
pi.pop(0)
pi.pop(0)

m = numpy.zeros(100).reshape((10, 10))

for i in range(0, len(pi)):
    try:
        m[pi[i], pi[i+1]] += 1  # count adjacent digits of pi
    except IndexError:
        pass

print(m)
print("Min: " + str(m.min()))
print("Max: " + str(m.max()))
print("Mode: " + str(stats.mode(m)))
예제 #45
0
from bigfloat import precision, setcontext, BigFloat

setcontext(precision(500))

f = BigFloat(0.1)
print f
for i in xrange(10000):
    f /= 2
print f
예제 #46
0
# Deal with overflow in exp using numpy
import bigfloat

bigfloat.exp(5000, bigfloat.precision(100))
# -&gt; BigFloat.exact('2.9676283840236670689662968052896e+2171', precision=100)
예제 #47
0
파일: base2.py 프로젝트: maurolacy/Babel
#!/usr/bin/python

from bigfloat import const_pi, precision

import math
import itertools

def convert_base(x, base=3, precision=None):
    length_of_int = int(math.log(x, base))
    iexps = range(length_of_int, -1, -1)
    if precision == None:
        fexps = itertools.count(-1, -1)
    else:
        fexps = range(-1, -int(precision + 1), -1)

    def cbgen(x, base, exponents):
        for e in exponents:
            d = int(x // (base ** e))
            x -= d * (base ** e)
            yield d
            if x == 0 and e < 0: break

    return cbgen(int(x), base, iexps), cbgen(x - int(x), base, fexps)

gi, gf = convert_base(float(const_pi(precision(1000))), base=10)
print ''.join(map(str, gf))
예제 #48
0
파일: pi4.py 프로젝트: maurolacy/Babel
#!/usr/bin/python

from bigfloat import const_pi, precision
from string import digits, maketrans, translate
print translate(str(const_pi(precision(24746))), maketrans(digits, 'rd\neHwlo! '))
#print
#print translate(str(const_pi(precision(5482))), maketrans(digits, '.Hdlro lwe'))
예제 #49
0
파일: problem26.py 프로젝트: jreese/euler
def longest_repeat(d):
    context = bigfloat.precision(precision)
    result_float = bigfloat.div(1, d, context=context)
    result = str(result_float)[2:].strip('0')[:-fuzz]
    result_len = len(result)

    #print "d = {0}, result = {1}".format(d, result)

    longest = ''
    longest_len = 0
    found = set()

    for i in range(result_len):
        remaining = result[i:]

        for k in range(i+1, result_len):
            substr = result[i:k]
            substr_len = len(substr)

            if substr == '0' * substr_len:
                continue

            new_substr = True
            for f in found:
                if substr == f:
                    new_substr = False
                elif is_repeating(f, substr):
                    new_substr = False

            if not new_substr:
                continue

            #print "new substring {0}".format(substr)

            repeats = is_repeating(substr, remaining)

            #print "substring {0} repeats {1} times".format(substr, repeats)

            if repeats >= min_repeats:
                #print "found repeating substring {0} (occurred {1} times)".format(substr, repeats, i=i, k=k)

                found.add(substr)

                if longest_len < substr_len:
                    #print "new longest substr!"
                    longest = substr
                    longest_len = substr_len

            if remaining[1:] == remaining[1] * len(remaining[1:]):
                #print "remaining string is all the same"
                break

        if found:
            #print "Already found repeating substrings, short-circuiting"
            break

        if remaining == remaining[0] * len(remaining):
            #print "remaining string is all the same"
            break

    if longest:
        #print "longest substring for d = {0} is {1}".format(d, longest)
        pass

    return longest
예제 #50
0
#!/usr/bin/env python

from bigfloat import sqrt, precision
from pe_tools import is_square

def hundred_digit_sum(n):
    s = str(n)
    if '.' in s:
        i = s.find('.')
        s = s[:i] + s[i+1:]
    s = s[:100]
    return sum(map(int, s))

if __name__ == '__main__':
    total = 0
    for n in range(1, 100):
        if not is_square(n):
            s = hundred_digit_sum(sqrt(n, precision(340)))
            total += s
    print str(total)
예제 #51
0
class JMM:
    def __init__(self):
        self.a = self.b = None

    def __iter__(self):
        for value in self.values():
            self.a, self.b = self.b, value
            yield value

    def values(self):
        yield Fraction(2, 1)
        yield Fraction(-4, 1)
        while True:
            def f(y, z):
                a = Fraction(111, 1)
                b = Fraction(1130, 1) / y
                c = Fraction(3000, 1) / (z * y)
                return a - b + c
            yield f(self.b, self.a)


print(list(take(10, JMM())))

with precision(9000):
    for a, b in zip(forever(0), JMM()):
        fnumerator   = BigFloat(b.numerator)
        fdenominator = BigFloat(b.denominator)
        big = fnumerator / fdenominator
        strbig = str(big)[:140]
        print(f"{a:>5}: {strbig} {b}")
예제 #52
0
#!/usr/bin/env python
import itertools
import os
import math
import bigfloat
from collections import defaultdict

# bfcontext = bigfloat.quadruple_precision
bfcontext = bigfloat.precision(1024)


def readverts(f):
    #    P = []
    #    for line in f:
    #        P.append(tuple(map(int, line.split(','))))
    P = map(lambda line: tuple(map(int, line.split(","))), f)
    return P


def angle_diff(a, b):
    diff = a - b
    twopi = 2.0 * math.pi
    while diff < 0.0:
        diff += twopi
    while diff >= twopi:
        diff -= twopi
    return diff


def bfangle_diff(a, b):
    diff = a - b
예제 #53
0
def get_pi_with_bigfloat(precision_in_bits):
    """precision is given in bits"""
    from bigfloat import precision
    import bigfloat
    # cut "3." off
    return str(bigfloat.atan2(+0.0,-0.0,precision(precision_in_bits)))[2:]
예제 #54
0
        return d

def MultiBuddhabrot(numprocs, secs, its, width, height, rect=draw.FloatRect(2)):
    manager = multiprocessing.Manager()
    rlist = manager.list()
    def fn(rlist):
        print "start"
        bud = Buddhabrot(secs, its, width, height, rect)
        bud.populate()
        rlist.append(bud)
    procs = [multiprocessing.Process(target=fn,args=(rlist,)) for i in xrange(numprocs)]
    [p.start() for p in procs]
    [p.join() for p in procs]
    result = Buddhabrot(secs, its, width, height, rect)
    for bud in rlist:
        result.data += bud.data
    return result
        

if __name__ == '__main__':
    bigfloat.setcontext(bigfloat.precision(52))
    #man = Mandlebrot(100)
    #d = draw.Draw(1024, 1024, draw.FloatRect(2.0))
#    bud = MultiBuddhabrot(8, 10, [20,200,2000], 1024, 1024)
#    bud.pickle("man.pck")
    bud = cPickle.load(open("man.pck", "rb"))
    bud.unpickle("man.npy")
    d = bud.draw()
    d.save("/vagrant/man.png")
    
예제 #55
0
    for c in reversed(num_coeffs):
        num = num * z + c
    den = 0.0
    for c in reversed(den_coeffs):
        den = den * z + c
    return num/den


def gamma(z, g, N):
    return (z+g-0.5)**(z-0.5) / exp(z+g-0.5) * L(g, z, N)


# Now express everything as a rational function;  we want to be
# able to figure out the coefficient of p_j z^k in the numerator.
# Let's call this coefficient b(j, k).  It depends on N.
# b(j, N)[k] is the coefficient of p_j z^k in the numerator.
# except: b(0, N)[k] is the coefficient of p_0/2 z^k in the numerator.

p = 300  # bits of precision to use for computation
g = bigfloat.BigFloat(6.024680040776729583740234375)
N = 13

with bigfloat.precision(p):
    print("Numerator coefficients:")
    for c in Lg_num_coeffs(g, N):
        print(c)

    print("Denominator coefficients:")
    for c in Lg_den_coeffs(g, N):
        print(c)