예제 #1
0
def max_precision(values):
    """
    Given a series of values (such as a :class:`.Column`) returns the most
    significant decimal places present in any value.

    :param values:
        The values to analyze.
    """
    max_whole_places = 1
    max_decimal_places = 0
    precision = getcontext().prec

    for value in values:
        if value is None or math.isnan(value) or math.isinf(value):
            continue

        sign, digits, exponent = value.normalize().as_tuple()

        exponent_places = exponent * -1
        whole_places = len(digits) - exponent_places

        if whole_places > max_whole_places:
            max_whole_places = whole_places

        if exponent_places > max_decimal_places:
            max_decimal_places = exponent_places

    # In Python 2 it was possible for the total digits to exceed the
    # available context precision. This ensures that can't happen. See #412
    if max_whole_places + max_decimal_places > precision:  # pragma: no cover
        max_decimal_places = precision - max_whole_places

    return max_decimal_places
예제 #2
0
파일: utils.py 프로젝트: skorasaurus/agate
def max_precision(values):
    """
    Given a series of values (such as a :class:`.Column`) returns the most
    significant decimal places present in any value.

    :param values:
        The values to analyze.
    """
    max_whole_places = 1
    max_decimal_places = 0
    precision = getcontext().prec

    for value in values:
        if value is None:
            continue

        sign, digits, exponent = value.normalize().as_tuple()

        exponent_places = exponent * -1
        whole_places = len(digits) - exponent_places

        if whole_places > max_whole_places:
            max_whole_places = whole_places

        if exponent_places > max_decimal_places:
            max_decimal_places = exponent_places

    # In Python 2 it was possible for the total digits to exceed the
    # available context precision. This ensures that can't happen. See #412
    if max_whole_places + max_decimal_places > precision:  # pragma: no cover
        max_decimal_places = precision - max_whole_places

    return max_decimal_places
예제 #3
0
def pi_cdecimal(prec):
    """cdecimal"""
    C.getcontext().prec = prec
    D = C.Decimal
    lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(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
예제 #4
0
 def __init__(self, c_ctx=C.getcontext(), p_ctx=P.getcontext()):
     """Initialization is from the C context"""
     self.c = c_ctx
     self.p = p_ctx
     self.p.prec = self.c.prec
     self.p.Emin = self.c.Emin
     self.p.Emax = self.c.Emax
     self.p.rounding = RoundMap[self.c.rounding]
     self.p.capitals = self.c.capitals
     self.settraps([sig for sig in self.c.traps if self.c.traps[sig]])
     self.setstatus([sig for sig in self.c.flags if self.c.flags[sig]])
     self.p.clamp = self.c.clamp
예제 #5
0
 def __init__(self, mpdctx=cdecimal.getcontext()):
     """Initialization is from the cdecimal context"""
     self.f = mpdctx
     self.d = decimal.getcontext()
     self.d.prec = self.f.prec
     self.d.Emin = self.f.Emin
     self.d.Emax = self.f.Emax
     self.d.rounding = decround[self.f.rounding]
     self.d.capitals = self.f.capitals
     self.settraps([sig for sig in self.f.traps if self.f.traps[sig]])
     self.setstatus([sig for sig in self.f.flags if self.f.flags[sig]])
     self.d._clamp = self.f._clamp
예제 #6
0
 def __init__(self, c_ctx=C.getcontext(), p_ctx=P.getcontext()):
     """Initialization is from the C context"""
     self.c = c_ctx
     self.p = p_ctx
     self.p.prec = self.c.prec
     self.p.Emin = self.c.Emin
     self.p.Emax = self.c.Emax
     self.p.rounding = RoundMap[self.c.rounding]
     self.p.capitals = self.c.capitals
     self.settraps([sig for sig in self.c.traps if self.c.traps[sig]])
     self.setstatus([sig for sig in self.c.flags if self.c.flags[sig]])
     self.p.clamp = self.c.clamp
예제 #7
0
    def __init__(self, tau, paso_decremento=0, intervalo_decremento=0):
        u"""
        Inicializador Softmax.

        :param tau: Parámetro Tau de la técnica.
        :param paso_decremento: Valor flotante con el que se decrementará el parámetro general.
        :param intervalo_decremento: Intervalo de episodios entre los cuales se realizará el decremento.
        """
        super(Softmax, self).__init__(paso_decremento, intervalo_decremento)
        self._val_param_general = decimal.Decimal(tau)
        self._val_param_parcial = decimal.Decimal(tau)
        self._name = "Softmax"
        self._paso_decremento = decimal.Decimal(paso_decremento)
        self._intervalo_decremento = decimal.Decimal(intervalo_decremento)

        # Establecer cantidad de ranuras
        self.cant_ranuras = 100

        # Establecer precisión de decimales a 5 dígitos
        decimal.getcontext().prec = 2
예제 #8
0
        start = time.time()
        for i in range(10000):
            x = func(p)
        print("%s:" % func.__name__.replace("pi_", ""))
        print("result: %s" % str(x))
        print("time: %fs\n" % (time.time() - start))

print(
    "\n# ======================================================================"
)
print("#                               Factorial")
print(
    "# ======================================================================\n"
)

C.getcontext().prec = C.MAX_PREC

for n in [100000, 1000000, 10000000, 100000000]:

    print("n = %d\n" % n)

    start_calc = time.time()
    x = factorial(C.Decimal(n), 0)
    end_calc = time.time()
    start_conv = time.time()
    sx = str(x)
    end_conv = time.time()
    print("cdecimal:")
    print("calculation time: %fs" % (end_calc - start_calc))
    print("conversion time: %fs\n" % (end_conv - start_conv))
예제 #9
0
Decimals Module.

Functions and classes for handling decimal numbers.

'''

# Copyright (c) 2015 Thomas Anatol da Rocha Woelz
# All rights reserved.
# BSD type license: check doc folder for details

__version__ = '1.0.0'
__docformat__ = 'restructuredtext'
__author__ = 'Thomas Anatol da Rocha Woelz'

try:
    import cdecimal as decimal
    from cdecimal import Decimal
except ImportError:
    print 'cdecimal not found, using standard (slower) decimal module'
    import decimal
    from decimal import Decimal

# all further rounding for decimal class is rounded up
decimal.getcontext().rounding = decimal.ROUND_UP

## example use:
#pi = Decimal('3.1415926535897931')
#round_pi = pi.quantize(Decimal('.01'))
#print round_pi
#3.14
예제 #10
0
    def __init__(self, resolution, lower_limits, upper_limits):

        MAX_UNITS = 20
        dim = len(lower_limits)
        dim_res = len(str(resolution))

        # if (resolution < 0.1) and ((dim*dim_res) > MAX_UNITS):
        if ((dim * dim_res) > MAX_UNITS):
            self.USE_DECIMAL_CLASS = True
            print "[DiscreteEnvironment] Using Decimal Class..."
        else:
            self.USE_DECIMAL_CLASS = False

        if self.USE_DECIMAL_CLASS:
            self.dtype = np.dtype(dec.Decimal)
        else:
            self.dtype = np.dtype(float)

        # Store the resolution
        self.resolution = [0.0] * dim
        # If resolution vesctor dimension doesn't math the space dimension,
        # the use it as a scalaer value
        if (type(resolution) is list):
            if (len(resolution) != dim):
                print "Resolution list length doesn't match space dimension"
                for idx in range(dim):
                    self.resolution[idx] = self.to_dec(resolution[0])
            else:
                for idx in range(dim):
                    self.resolution[idx] = self.to_dec(resolution[idx])

        else:
            for idx in range(dim):
                self.resolution[idx] = self.to_dec(
                    resolution)  # Resolution now works with very large range
        dec.getcontext().prec = 28

        # Store the bounds
        self.lower_limits = self.to_dec(lower_limits)  #np.array(lower_limits)
        self.upper_limits = self.to_dec(
            upper_limits
        )  #np.array(upper_limits) #np.array(upper_limits,dtype=self.dtype)
        self.lim_ranges = self.upper_limits - self.lower_limits

        # Calculate the dimension
        self.dimension = len(self.lower_limits)

        # Figure out the number of grid cells that are in each dimension
        self.num_cells = self.dimension * [0]
        for idx in range(self.dimension):
            self.num_cells[idx] = np.floor(
                (upper_limits[idx] - lower_limits[idx]) /
                float(self.resolution[idx]))

        self.dtype_num_cells = self.to_dec(self.num_cells)

        # Grid to index basis
        #self.to_dec(100.0)/self.resolution #max(self.to_dec(100.0)/self.resolution,max(self.num_cells))
        #self.basis_len = self.to_dec(max(self.num_cells))
        self.basis_len = self.to_dec(100.0) / min(self.resolution)
        if self.USE_DECIMAL_CLASS:
            self.basis_len = self.basis_len.to_integral()
        else:
            self.basis_len = round(self.basis_len)

        self.dtype_basis_len = self.to_dec(self.basis_len)
        self.basis = self.basis_len**self.to_dec(range(self.dimension))
        self.basis = self.basis[::-1]
__license__    = "GPL"
__maintainer__ = "Jack Peterson"
__email__      = "*****@*****.**"

# Python 3 compatibility
from six.moves import xrange as range
_IS_PYTHON_3 = sys.version_info[0] == 3
identity = lambda x : x
if _IS_PYTHON_3:
    u = identity
else:
    import codecs
    def u(string):
        return codecs.unicode_escape_decode(string)[0]

getcontext().rounding = ROUND_HALF_EVEN

class Oracle(object):

    def __init__(self, votes=None, decision_bounds=None, weights=-1,
                 catch_p=.1, max_row=5000, verbose=False):
        self.votes = ma.masked_array(votes, isnan(votes))
        self.decision_bounds = decision_bounds
        self.weights = weights
        self.catch_p = catch_p
        self.max_row = max_row
        self.verbose = verbose

    def WeightedMedian(self, data, weights):
        """Calculate a weighted median.
예제 #12
0
    iterations = 1

    if '--short' in sys.argv:
        samples = 1
        iterations  = 1
    elif '--medium' in sys.argv:
        samples = 1
        iterations = None
    elif '--long' in sys.argv:
        samples = 5
        iterations = None
    elif '--all' in sys.argv:
        samples = 100
        iterations = None

    all_context_methods = set(dir(cdecimal.getcontext()) + dir(decimal.getcontext()))
    all_cdec_methods = [m for m in dir(cdec) if m in all_context_methods]
    untested_methods = [m for m in all_context_methods if not (m in all_cdec_methods)]

    unary_methods = []
    binary_methods = []
    ternary_methods = []
    for m in all_cdec_methods:
        try:
            l = len(inspect.getargspec(getattr(cdec, m))[0])
        except TypeError:
            continue
        if   l == 1:
            unary_methods.append(m)
        elif l == 2:
            binary_methods.append(m)
예제 #13
0
import sys
import decimal 
import cdecimal
from random import random, randint
import time
  
usage = "usage: dec_vs_cdec.py datasize"
if len(sys.argv) < 2:
    print(usage)
    sys.exit()

m = int(sys.argv[1])
print("Data size is %d\n" % m)
print("decimal: {c}\n".format(c=decimal.getcontext()))
print("cdecimal: {c}\n".format(c=cdecimal.getcontext()))
print "-"*80

s = 0
start = time.time()
for x in xrange(1, m):
    s += randint(1,m)
print("integer: elapsed time={t} sum={s}".format(t=time.time() - start, s=s))
print "-"*80

s = 0
start = time.time()
for x in xrange(1, m):
    s += random()
print("float: elapsed time={t} sum={s}".format(t=time.time() - start, s=s))
print "-"*80
예제 #14
0
'''
Created on May 22, 2014

@author: xleon
'''

import simpy
from optparse import OptionParser

from cdecimal import getcontext, FloatOperation, ROUND_HALF_UP
import iosim
import importlib

# Initialize cdecimal module
c = getcontext()
c.prec = 12
c.traps[FloatOperation] = True
c.rounding = ROUND_HALF_UP

if __name__ == '__main__':
    # Parse command line
    parser = OptionParser()
    parser.set_default("num_users", 1)
    parser.set_default("num_files", 50)
    parser.set_default("file_size", 64)
    parser.set_default("block_size", 16)
    parser.set_default("replica_selection_policy", 1)
    parser.set_default("file_creation_policy", 0)
    parser.set_default("fanout", 3)
    parser.set_default("num_disks", 200)
    parser.set_default("num_disks_recovery", 50)
    def __init__(self, resolution, lower_limits, upper_limits):

        MAX_UNITS = 20
        dim = len(lower_limits)
        dim_res = len(str(resolution))

        # if (resolution < 0.1) and ((dim*dim_res) > MAX_UNITS):
        if ((dim*dim_res) > MAX_UNITS):
            self.USE_DECIMAL_CLASS = True
            print "[DiscreteEnvironment] Using Decimal Class..."
        else:
            self.USE_DECIMAL_CLASS = False

        if self.USE_DECIMAL_CLASS:
            self.dtype = np.dtype(dec.Decimal)
        else:
            self.dtype = np.dtype(float)

        # Store the resolution
        self.resolution = [0.0] * dim
        # If resolution vesctor dimension doesn't math the space dimension,
        # the use it as a scalaer value
        if (type(resolution) is list):
            if (len(resolution) != dim):
                print "Resolution list length doesn't match space dimension"
                for idx in range(dim):
                    self.resolution[idx] = self.to_dec(resolution[0])
            else:
                for idx in range(dim):
                    self.resolution[idx] = self.to_dec(resolution[idx])

        else:
            for idx in range(dim):
                self.resolution[idx] = self.to_dec(resolution)    # Resolution now works with very large range
        dec.getcontext().prec = 28

        # Store the bounds
        self.lower_limits = self.to_dec(lower_limits) #np.array(lower_limits)
        self.upper_limits = self.to_dec(upper_limits) #np.array(upper_limits) #np.array(upper_limits,dtype=self.dtype)
        self.lim_ranges = self.upper_limits - self.lower_limits

        # Calculate the dimension
        self.dimension = len(self.lower_limits)

        # Figure out the number of grid cells that are in each dimension
        self.num_cells = self.dimension*[0]
        for idx in range(self.dimension):
            self.num_cells[idx] = np.floor((upper_limits[idx] - lower_limits[idx])/float(self.resolution[idx]))

        self.dtype_num_cells = self.to_dec(self.num_cells)

        # Grid to index basis
        #self.to_dec(100.0)/self.resolution #max(self.to_dec(100.0)/self.resolution,max(self.num_cells))
        #self.basis_len = self.to_dec(max(self.num_cells))
        self.basis_len = self.to_dec(100.0)/min(self.resolution)
        if self.USE_DECIMAL_CLASS:
            self.basis_len = self.basis_len.to_integral()
        else:
            self.basis_len = round(self.basis_len)


        self.dtype_basis_len = self.to_dec(self.basis_len)
        self.basis = self.basis_len**self.to_dec(range(self.dimension))
        self.basis = self.basis[::-1]
예제 #16
0
    bool_type,
    float_type,
    bytes_type,
    bytearray_type,
    none_type,
    date_type,
    time_type,
    datetime_type,
}

try:
    import cdecimal as _decimal
except:
    import decimal as _decimal

default_decimal_context = _decimal.getcontext()
_decimal2str = default_decimal_context.to_eng_string

import datetime

try:
    from base64 import encodebytes, decodebytes
except:
    from base64 import encodestring as encodebytes, decodestring as decodebytes


class PyInt:
    def __init__(self, val):
        self.val = val

    def __repr__(self):