예제 #1
0
 def float_to_decimal(self, f):
     "Convert a floating point number to a Decimal with no loss of information"
     n, d = f.as_integer_ratio()
     numerator, denominator = Decimal(n), Decimal(d)
     ctx = Context(prec=60)
     result = ctx.divide(numerator, denominator)
     while ctx.flags[Inexact]:
         ctx.flags[Inexact] = False
         ctx.prec *= 2
         result = ctx.divide(numerator, denominator)
     return result
예제 #2
0
def float_to_decimal(f):
    "Convert a floating point number to a Decimal with no loss of information"
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #3
0
def float_to_decimal(f):
    """Convert a floating point number to a Decimal with no loss of information.
        See: http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq
    """
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #4
0
def float_to_decimal(f):
    """Convert a floating point number to a Decimal with no loss of information.
        See: http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq
    """
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #5
0
def float_to_decimal(f):
    """
        Convert a floating point number to a Decimal with no loss of information.
        Intended for Python 2.6 where casting float to Decimal does not work.
    """
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #6
0
def fundamental_solution(N):
    context = Context(prec=1000)
    val = Decimal(context.sqrt(N))
    rep = [floor(val)]
    val = Decimal(
        context.divide(1, (context.subtract(val, Decimal(floor(val))))))
    rep.append(floor(val))
    ctr = 1

    h_base = [0, 1]
    k_base = [1, 0]

    h_1 = rep[0] * h_base[-1] + h_base[-2]
    k_1 = rep[0] * k_base[-1] + k_base[-2]

    if check_sol(h_1, k_1, N):
        return h_1, k_1

    h_2 = rep[1] * h_1 + h_base[-1]
    k_2 = rep[1] * k_1 + k_base[-1]

    if check_sol(h_2, k_2, N):
        return h_2, k_2

    H = [h_1, h_2]
    K = [k_1, k_2]

    h = h_2
    k = k_2

    ind = 3
    frac = Fraction(int(h), int(k))

    while not (check_sol(frac.numerator, frac.denominator, N)):

        val = Decimal(
            context.divide(1, (context.subtract(val, Decimal(floor(val))))))
        rep.append(floor(val))
        #val = rep[ind-1]
        h = long(long(floor(val)) * H[-1] + H[-2])
        k = long(long(floor(val)) * K[-1] + K[-2])

        frac = Fraction(long(h), long(k))

        H.append(frac.numerator)
        K.append(frac.denominator)
        ind += 1

    return h, k
예제 #7
0
def float_to_decimal(f):
    "Convert a floating point number to a Decimal with no loss of information"
    if f in _special_floats:
        return _special_floats[f]
    elif math.isnan(f):
        return Decimal('NaN')
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #8
0
def float_to_decimal(f):
    """
    Convert a floating point number to a Decimal with
    no loss of information. Intended for Python 2.6 where
    casting float to Decimal does not work.
    """
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = Context(prec=60)
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
        result = ctx.divide(numerator, denominator)
    return result
예제 #9
0
파일: compat.py 프로젝트: llnz/hypothesis
 def float_to_decimal(f):
     """Convert a floating point number to a Decimal with no loss of
     information."""
     if f in _special_floats:
         return _special_floats[f]
     elif math.isnan(f):
         return Decimal(u'NaN')
     n, d = f.as_integer_ratio()
     numerator, denominator = Decimal(n), Decimal(d)
     ctx = Context(prec=60)
     result = ctx.divide(numerator, denominator)
     while ctx.flags[Inexact]:
         ctx.flags[Inexact] = False
         ctx.prec *= 2
         result = ctx.divide(numerator, denominator)
     return result
예제 #10
0
파일: misc.py 프로젝트: rumpelt/PyMathApp
def calculatebmi(listpr):
    c = Context()
    for p in listpr:
        for timeattr in p.getalltimeattribute():
            if timeattr.getattribute("HEIGHT") is not None and timeattr.getattribute("WEIGHT") is not None:
                bmi = c.divide(timeattr.getattribute("HEIGHT"), c.power(timeattr.getattribute("WEIGHT"), Decimal("2")))
                timeattr.setattribute("BMI", bmi)
예제 #11
0
def task_info_page(request):
	context = {}
	task_info = ts.objects.all()[0]
	# task_info = get_list_or_404(ts, theExaminer = request.user).lastest('submitTime')
	today = timezone.now()
	if task_info : 
		last_update = task_info.submitTime
		if ((last_update.year == today.year) and (last_update.month == today.month)) :
			# get and calc task info
			decimalContext = Context(prec = 4)	# set Decimal precision
			# yi tong
			context['yiTongRenWuLiang'] = mt(theExaminer=request.user, year = today.year, month = today.month).objects.monthlyTask
			context['yiChuAn'] = task_info.yiChuAn
			context['xyJian'] = task_info.xyJian
			context['xyLv'] = task_info.xyJian / task_info.yiChuAn
			context['yiTongLv'] = decimalContext.divide(task_info.yiChuAn, Decimal(8.05)) * 100
			#jie an
			context['jieAnRenWuLiang'] = 2
			context['shouQuan'] = task_info.shouQuan
			context['boHui'] = task_info.boHui
			context['shiChe'] = task_info.shiChe
			context['jieAnLiang'] = decimalContext.add( \
						decimalContext.add(context['shouQuan'], context['boHui']), \
						context['shiChe'])
			context['jieAnLv'] = decimalContext.divide(context['jieAnLiang'], Decimal(context['jieAnRenWuLiang'])) * 100
		else:
			# get and calc task info
			decimalContext = Context(prec = 4)	# set Decimal precision
			# yi tong
			context['yiTongRenWuLiang'] = 8.05
			context['yiChuAn'] = 0
			context['xyJian'] = 0
			context['xyLv'] = 0
			context['yiTongLv'] = decimalContext.divide(0, Decimal(8.05)) * 100
			#jie an
			context['jieAnRenWuLiang'] = 2
			context['shouQuan'] = 0
			context['boHui'] = 0
			context['shiChe'] = 0
			context['jieAnLiang'] = 0
			context['jieAnLv'] = 0 * 100
	

	return render(request, 'task_submit/task_info.html', context)
예제 #12
0
def cont_frac(N):
    context = Context(prec=1000)
    val = Decimal(context.sqrt(N))
    rep = [floor(val)]
    ctr = 1
    while ctr <= 1000:
        val = Decimal(
            context.divide(1, (context.subtract(val, Decimal(floor(val))))))
        rep.append(floor(val))
        ctr += 1
    return rep
예제 #13
0
class _Amount:
    def __init__(self, fraction_digits: int, precision: int):
        self._ctx = Context(prec=precision, rounding=ROUND_HALF_EVEN)

        self._fraction_digits = fraction_digits
        self._precision = precision
        self._quantizer = self._ctx.create_decimal(1).scaleb(-fraction_digits)

        self._value = self._ctx.create_decimal(0)

    def deserialize(self, serialized_value):
        self._value = (
            self._ctx.create_decimal(serialized_value)
            .scaleb(-self._fraction_digits)
            .quantize(self._quantizer)
        )
        return self

    def serialize(self) -> int:
        return int(self._value.scaleb(self._fraction_digits))

    def set(self, value: Decimal):
        self._value = self._ctx.create_decimal(value).quantize(self._quantizer)
        return self

    def clone(self):
        raise NotImplementedError

    def __str__(self):
        return str(self._value)

    def __imul__(self, other):
        operand = other._value if isinstance(other, Amount) else other
        value = self._ctx.multiply(self._value, operand)
        return self.set(value)

    def __itruediv__(self, other):
        operand = other._value if isinstance(other, Amount) else other
        value = self._ctx.divide(self._value, operand)
        return self.set(value)

    def __mul__(self, other):
        return self.clone().__imul__(other)

    def __truediv__(self, other):
        return self.clone().__itruediv__(other)

    def __iadd__(self, other):
        operand = other._value if isinstance(other, Amount) else other
        value = self._ctx.add(self._value, operand)
        return self.set(value)

    def __add__(self, other):
        return self.clone().__iadd__(other)
예제 #14
0
def cont_frac(N):
    context = Context(prec=1000)
    val = Decimal(context.sqrt(N))
    init_val = floor(val)
    rep = [init_val]
    ctr = 1
    while floor(val) != 2 * init_val:
        val = Decimal(
            context.divide(1, (context.subtract(val, Decimal(floor(val))))))
        rep.append(floor(val))
        ctr += 1
    return rep
예제 #15
0
    return x


txt = open('../data/don_quixote.txt', 'r').read()
src = source(txt)
letters, count = map(list, zip(*src))
probs = [x / sum(count) for x in count]
p = min(probs)
k = ceil(-log(p, 2) + 2)

l = 1000
for _ in range(1000):
    i = min(randrange(len(txt)), len(txt) - l)
    str = txt[i:i + l]

    c = arithmetic_encode(str, src, k)
    print(c)

    ctx = Context()
    d = dict(zip(letters, probs))
    pr = reduce(lambda x, y: ctx.multiply(x, Decimal(d[y])), str, Decimal(1))
    expected_length = ceil(-ctx.divide(pr.ln(ctx), Decimal(2).ln(ctx))) + 1
    actual_length = len(c)
    assert (actual_length <= expected_length)

    dec = arithmetic_decode(c, src, k, len(str))
    print(dec)

    assert (dec == str)
예제 #16
0
 print(neginf + inf)
 print(neginf * inf)
 try:
     print(dig / 0)
 except Exception as e:
     print("Division by zero")
 getcontext().traps[DivisionByZero] = 1
 try:
     print(dig / 0)
 except Exception as e:
     print("Division by zero")
 c = Context()
 c.traps[InvalidOperation] = 0
 print(+c.flags[InvalidOperation])
 try:
     c.divide(Decimal(0), Decimal(0))
 except Exception as e:
     print("Division by zero")
 c.traps[InvalidOperation] = 1
 print(+c.flags[InvalidOperation])
 c.flags[InvalidOperation] = 0
 print(+c.flags[InvalidOperation])
 try:
     print(c.divide(Decimal(0), Decimal(0)))
 except Exception as e:
     print("Division by zero")
 print(+c.flags[InvalidOperation])
 try:
     print(c.divide(Decimal(0), Decimal(0)))
 except Exception as e:
     print("Division by zero")
예제 #17
0
def learn_naivebayes_text(texts=[], min_word_size=4):
	from datetime import datetime as date
	from decimal import Decimal, Context 
	
	# cria contexto para o built-in Decimal
	context = Context()

	if type(texts).__name__ == 'list':
		print('Preparando dados')
		proc_texts = prepare_reuters_data(texts, 
						min_word_size=min_word_size)
	else:
		proc_texts = texts
	
	print('\n\nCalculo das probabilidades\n')
	
	# cria vocabulario e ja conta ocorrencias de palavas
	# por texto
	vocabulary = set()
	freq_words = []
	index = 0 
	for text in proc_texts['texts']:
		
		# contagem das palavras
		freq_words.append({})
		for word in text:
			if not word in freq_words[index]:
				freq_words[index][word] = 0
			freq_words[index][word] += 1
		
		# criacao do vocabulario
		vocabulary.update(text)
		index += 1
	
	# ja adiciona um para evitar a prob ser zero
	vocabulary_size = len(vocabulary)
	vocab_freq = {}
	for word in vocabulary:
		vocab_freq[word] = 1
	
	# calculando P_topicj e P_wk__topicj
	topics = {}
	total_texts = len(proc_texts['texts'])
	for topic, text_indices in proc_texts['topics'].items():
		
		print("\t" + date.now().strftime('[%Y-%m-%d %H:%M:%S]')
			+ " topico: %s" % topic)

		topics[topic] = {
			'P_topic': Decimal( len(text_indices) / total_texts),
			'P_wk': vocab_freq
		}
		
		# itera os textos do topico em questao
		total_words = 0
		for text in text_indices:
			for word, freq in freq_words[text].items():
				topics[topic]['P_wk'][word] += freq
			total_words += len(freq_words[text])
		
		# frequencia das palavras para o topico em questao
		# ja contadas, e acrescidas de 1, para evitar o zero
		# agora calcula a prob real da palavra dado o topico
		for word, freq in topics[topic]['P_wk'].items():
			topics[topic]['P_wk'][word] = context.divide(
			Decimal(freq), Decimal(total_words + vocabulary_size))
		
		# crio uma palavra nao existente como um marcador para 
		# palavras nao vistas
		topics[topic]['P_wk']['espuria'] = context.divide(
			Decimal(1), Decimal(total_words + vocabulary_size))

	print('\n\nTopicos processados: %d' % len(topics.keys()))
	print('Tamanho do vocabulario: %d' % vocabulary_size)
	
	return topics
예제 #18
0
def learn_naivebayes_text(texts=[], min_word_size=4):
    from datetime import datetime as date
    from decimal import Decimal, Context

    # cria contexto para o built-in Decimal
    context = Context()

    if type(texts).__name__ == 'list':
        print('Preparando dados')
        proc_texts = prepare_reuters_data(texts, min_word_size=min_word_size)
    else:
        proc_texts = texts

    print('\n\nCalculo das probabilidades\n')

    # cria vocabulario e ja conta ocorrencias de palavas
    # por texto
    vocabulary = set()
    freq_words = []
    index = 0
    for text in proc_texts['texts']:

        # contagem das palavras
        freq_words.append({})
        for word in text:
            if not word in freq_words[index]:
                freq_words[index][word] = 0
            freq_words[index][word] += 1

        # criacao do vocabulario
        vocabulary.update(text)
        index += 1

    # ja adiciona um para evitar a prob ser zero
    vocabulary_size = len(vocabulary)
    vocab_freq = {}
    for word in vocabulary:
        vocab_freq[word] = 1

    # calculando P_topicj e P_wk__topicj
    topics = {}
    total_texts = len(proc_texts['texts'])
    for topic, text_indices in proc_texts['topics'].items():

        print("\t" + date.now().strftime('[%Y-%m-%d %H:%M:%S]') +
              " topico: %s" % topic)

        topics[topic] = {
            'P_topic': Decimal(len(text_indices) / total_texts),
            'P_wk': vocab_freq
        }

        # itera os textos do topico em questao
        total_words = 0
        for text in text_indices:
            for word, freq in freq_words[text].items():
                topics[topic]['P_wk'][word] += freq
            total_words += len(freq_words[text])

        # frequencia das palavras para o topico em questao
        # ja contadas, e acrescidas de 1, para evitar o zero
        # agora calcula a prob real da palavra dado o topico
        for word, freq in topics[topic]['P_wk'].items():
            topics[topic]['P_wk'][word] = context.divide(
                Decimal(freq), Decimal(total_words + vocabulary_size))

        # crio uma palavra nao existente como um marcador para
        # palavras nao vistas
        topics[topic]['P_wk']['espuria'] = context.divide(
            Decimal(1), Decimal(total_words + vocabulary_size))

    print('\n\nTopicos processados: %d' % len(topics.keys()))
    print('Tamanho do vocabulario: %d' % vocabulary_size)

    return topics