示例#1
0
def get_coinone():
    getcontext().prec = 6
    return async_stubber(
        Decimal("300.396").quantize(WEI_VALUE, context=Context(prec=40)))
    so that we can report N < 15"""
    n = int(n)
    assert n == math.floor(
        n)  # make sure it is an integer; shouldn't be needed with above
    assert n >= 0
    if 0 <= n < 15: return LESS_THAN_15
    if 15 <= n <= 99: return str(nearest(n, 10))
    if 100 <= n <= 999: return str(nearest(n, 50))
    if 1000 <= n <= 9999: return str(nearest(n, 100))
    if 10000 <= n <= 99999: return str(nearest(n, 500))
    if 100000 <= n <= 999999: return str(nearest(n, 1000))
    return round_decimal(n)


from decimal import Decimal, ROUND_HALF_EVEN, Context
prec4_rounder = Context(prec=4, rounding=ROUND_HALF_EVEN)


def round4_float(f):
    return float(str(prec4_rounder.create_decimal(f)))


def determine_rounding_method(s):
    if "." in s:
        return ROUND4_METHOD
    else:
        return COUNTS_METHOD


def round_str(org, add_spaces=True, method=None):
    """Take a string, convert it to a number, and round it. Add spaces if
示例#3
0
# -*- coding: UTF-8 -*-
#
# copyright: 2020-2021, Frederico Martins
# author: Frederico Martins <http://github.com/fscm>
# license: SPDX-License-Identifier: MIT
"""Tests for the Boliviano representation."""

from decimal import Context
from pytest import raises
from multicurrency import Currency, Boliviano
from multicurrency import (CurrencyMismatchException, CurrencyTypeException)

CONTEXT = Context(prec=28, rounding='ROUND_HALF_EVEN').copy()


def test_boliviano():
    """test_boliviano."""
    amount = CONTEXT.create_decimal(1) / CONTEXT.create_decimal(7)
    boliviano = Boliviano(amount=amount)
    decimal = CONTEXT.create_decimal(amount)
    assert boliviano.amount == decimal
    assert boliviano.numeric_code == '068'
    assert boliviano.alpha_code == 'BOB'
    assert boliviano.decimal_places == 2
    assert boliviano.decimal_sign == ','
    assert boliviano.grouping_sign == '.'
    assert not boliviano.international
    assert boliviano.symbol == 'Bs.'
    assert boliviano.symbol_ahead
    assert boliviano.symbol_separator == '\u00A0'
    assert boliviano.convertion == ''
"""
Chapter 15 Homework    
"""

# Problem 1: Precision
# This chapter introduced us to with statements. Many of us are already familiar with this for file handlers.
# What about for other use cases?

from decimal import Decimal, localcontext, Context

# use the above modules to compute the difference between the representation of 22/7 at 50 precision vs 28 precision
# write the difference with 20 precision

with localcontext(Context(prec=28)):
    x = Decimal(22) / Decimal(7)

with localcontext(Context(prec=50)):
    y = Decimal(22) / Decimal(7)

with localcontext(Context(prec=20)):
    print(x - y)

# Problem 2: Timeout
# Implement a class that timeouts after some input time
# make this class compatible in a with clause
from time import sleep

# Solution 1: Signal
# The standard solution is to use signal

import signal
示例#5
0
 def __init__(self) -> None:
     self._context = Context(prec=4, rounding=ROUND_DOWN)
     self.start_time = 0.0
     self.end_time = 0.0
示例#6
0
import datetime
from decimal import Decimal, Context, ROUND_HALF_UP
import time
import logging
from django.conf import settings

logger = logging.getLogger('django')
max_datetime = datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
max_time_stamp = time.mktime(max_datetime.timetuple())
create_token_decimals = Context(prec=6).create_decimal
create_usd_decimals = Context(prec=3).create_decimal


def sqlGenerateOrList(param_name, count, operation):
    index = 0
    sql_string = ''
    while index < count:
        sql_string += '{} {} %s'.format(param_name, operation)
        if index != count - 1:
            sql_string += ' OR '
        index += 1
    return sql_string


def extractInParams(request, equals_param, in_param):
    included_values = []
    equals = request.GET.get(equals_param, None)
    includes_raw = request.GET.get(in_param, None)
    if equals:
        included_values.append(equals)
    if includes_raw:
示例#7
0
文件: format.py 项目: olegsv/dex-cli
def format_amount(amount, decimals=18, rounding=ROUND_DOWN):
  quantize_value = Decimal(10) ** -Decimal(decimals)
  rounded_value = Decimal(amount).quantize(quantize_value, context=Context(prec=40), rounding=rounding)

  return f'{rounded_value:,.{decimals}f}'.rstrip('0').rstrip('.')
示例#8
0
import csv
import gc
import json
from datetime import datetime, date
from decimal import Decimal, Context, setcontext
from os import path, environ, getenv
from multiprocessing import Pool, cpu_count

import click
from spectrify.utils.timestamps import iso8601_to_nanos, iso8601_to_days_since_epoch
from spectrify.utils.parquet import Writer
from spectrify.utils.s3 import S3GZipCSVReader

# Redshift allows up to 38 bits of decimal/numeric precision. Set the Python
# decimal context accordingly
redshift_context = Context(prec=38)
setcontext(redshift_context)

# This determines the number of rows in each row group of the Parquet file.
# Larger row group means better compression.
# Larger row group also means more memory required for write.
# Assuming a row size of 2KB, this will process approx. 500MB of data per group.
# Actual memory usage will be some multiple of that, since multiple copies
# are required in memory for processing.
SPECTRIFY_ROWS_PER_GROUP = environ.get('SPECTRIFY_ROWS_PER_GROUP') or 250000

# Python2 csv builtin library has limited support with unicode CSVs
# (see: https://github.com/hellonarrativ/spectrify/issues/16).
# Therefore, there is an option to replace the builtin csv module with `unicodecsv` module.
# By default this option is disabled - `unicodecsv` can have a pretty serious performance
# impact.
示例#9
0
from decimal import Decimal, Context, ROUND_FLOOR, setcontext

C = Context(rounding=ROUND_FLOOR)
setcontext(C)

x1, y1, x2, y2 = map(Decimal, input().split())
r_2 = (x2 - x1)**2 + (y2 - y1)**2
print(C.sqrt(r_2))
示例#10
0
from .schema import extract_record_type, extract_logical_type, parse_schema
from ._schema_common import SCHEMA_DEFS
from ._read_common import (SchemaResolutionError, MAGIC, SYNC_SIZE,
                           HEADER_SCHEMA, missing_codec_lib)
from ._timezone import epoch
from .const import (MCS_PER_HOUR, MCS_PER_MINUTE, MCS_PER_SECOND, MLS_PER_HOUR,
                    MLS_PER_MINUTE, MLS_PER_SECOND, DAYS_SHIFT)

MASK = 0xFF
AVRO_TYPES = {
    'boolean', 'bytes', 'double', 'float', 'int', 'long', 'null', 'string',
    'fixed', 'enum', 'record', 'error', 'array', 'map', 'union', 'request',
    'error_union'
}

decimal_context = Context()


def match_types(writer_type, reader_type):
    if isinstance(writer_type, list) or isinstance(reader_type, list):
        return True
    if isinstance(writer_type, dict) or isinstance(reader_type, dict):
        return match_schemas(writer_type, reader_type)
    if writer_type == reader_type:
        return True
    # promotion cases
    elif writer_type == 'int' and reader_type in ['long', 'float', 'double']:
        return True
    elif writer_type == 'long' and reader_type in ['float', 'double']:
        return True
    elif writer_type == 'float' and reader_type == 'double':
示例#11
0
 def __init__(self, precision=2):
     self.empty()
     self._context = Context(prec=precision)
示例#12
0
from decimal import Decimal, Context, localcontext
v = Decimal('578')
with localcontext(Context(prec=16)):
    print(v.sqrt())
示例#13
0
def getConfigThroughWizard(defaultsDict=ConfigDefaults):
    try:
        answers = {}
        printQuestion("""\
            Do you want to enable simulation? Setting `simulation` to `True`
            allows you to run LibreSelery in a try state that does not
            pay out. No Coinbase token is needed in simulation.""")
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("simulation"),
                default=str(defaultsDict.get("simulation", "")),
                validator=BoolValidator(),
            ))
        if answer:
            print("Simulation Enabled. No payout.")
        else:
            print("Simulation Disabled.")
        answers["simulation"] = answer

        # Added "You probably want to do this enabled", because asking this question in the first place could be confusing.
        printQuestion(
            "Do you want to include contributors of the main project?")
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("include_main_repository"),
                default=str(defaultsDict.get("include_main_repository", "")),
                validator=BoolValidator(),
            ))
        if answer:
            print("Including contributors of main project")
        else:
            print("Excluding contributors of main project")
        answers["include_main_repository"] = answer

        printQuestion("Do you want to include your project dependencies?")
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("include_dependencies"),
                default=str(defaultsDict.get("include_dependencies", "")),
                validator=BoolValidator(),
            ))
        if answer:
            print("Dependencies will be included.")
        else:
            print("Dependencies will NOT be included.")
        answers["include_dependencies"] = answer

        printQuestion(
            "Do you want to invest in your tools listed in `tooling_repos.yml`?"
        )
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("include_tooling_and_runtime"),
                default=str(defaultsDict.get("include_tooling_and_runtime",
                                             "")),
            ))
        if answer:
            print("Tooling and Runtime will be included.")
        else:
            print("Tooling and Runtime has been disabled from inclusion.")
        answers["include_tooling_and_runtime"] = answer

        printQuestion("How many commits does a user need to be a contributor?")
        answer = int(
            prompt(
                makeColorPrompt("min_contributions_required_payout"),
                default=str(
                    defaultsDict.get("min_contributions_required_payout", "")),
                validator=IntegerValidator(),
            ))
        print(
            "A contributor will need at least %d commits to be included for payout."
            % answer)
        answers["min_contributions_required_payout"] = answer

        if answers["include_tooling_and_runtime"]:
            print(
                "To how many contributors of dependency projects do you want to payout to?"
            )
            answer = int(
                prompt(
                    makeColorPrompt("included_dependency_contributor"),
                    default=str(
                        defaultsDict.get("included_dependency_contributor",
                                         "")),
                    validator=IntegerValidator(),
                ))
            print(
                "%d contributors from the dependencies will receive funding." %
                answer)
            answers["included_dependency_contributor"] = answer

        printQuestion(
            "To evaluate the contribution of a user, there is a uniform weight attached equally to every contributor. What should this weight be?"
        )
        answer = int(
            prompt(
                makeColorPrompt("uniform_weight"),
                default=str(defaultsDict.get("uniform_weight", "")),
                validator=IntegerValidator(),
            ))
        print("The uniform base weight is set to %d" % answer)
        answers["uniform_weight"] = answer

        printQuestion(
            "The activity of a contributor is weighted as well. How much weight do you want to set for the activity?"
        )
        answer = int(
            prompt(
                makeColorPrompt("activity_weight"),
                default=str(defaultsDict.get("activity_weight", "")),
                validator=IntegerValidator(),
            ))
        answers["activity_weight"] = answer
        if answer == 0:
            print("The activity won't have an affect on the salary.")
        else:
            print("The activity weight is %s" % answer)

            printQuestion(
                "What activity do you want to take into consideration in "
                "payout calculation?")
            print("1: All commits.")
            print("2: All commits since the last version tag.")
            print("3: Last N commits.")  # last commit  # commit:HEAD~1
            print("4: custom string")
            # weight for weighted git commits

            activity_since_commit_value = defaultsDict.get(
                "activity_since_commit", "")
            defaultN = "1"
            defaultCustomStr = ""
            match = re.fullmatch(r"commit:HEAD~(\d+)",
                                 activity_since_commit_value)
            if activity_since_commit_value == "":
                default = "1"
            elif activity_since_commit_value == r"tag_regex:v?[0-9]+\.[0-9]+\.[0-9]+":
                default = "2"
            elif match:
                default = "3"
                defaultN = match[1]
            else:
                default = "4"
                defaultCustomStr = activity_since_commit_value

            answer = prompt(
                makeColorPrompt("activity_since_commit"),
                default=default,
                validator=IntegerValidator(min=1, max=4),
            )
            if answer == "1":
                pass
            elif answer == "2":
                answers[
                    "activity_since_commit"] = r"tag_regex:v?[0-9]+\.[0-9]+\.[0-9]+"
                print(r"Will use the following regex for tag:")
                print(r"v?[0-9]+\.[0-9]+\.[0-9]+")
            elif answer == "3":
                printQuestion(
                    "How many commits do you want to take into account?")
                answer = prompt(makeColorPrompt("N"),
                                default=defaultN,
                                validator=IntegerValidator())
                answers["activity_since_commit"] = "commit:HEAD~" + answer
                print("Will use last " + answer + " commits")
            elif answer == "4":
                printQuestion(
                    "What is the custom string that you want to use?")
                answer = prompt(makeColorPrompt("activity_since_commit"),
                                default=defaultCustomStr)
                answers["activity_since_commit"] = answer

        # full_split: weighted split over all contributors
        # random_split: random weighted split with equal payout per contributor
        printQuestion("""\
            For some payment services the fees can become significant if a
            large amount of transactions with a small investment
            is performed. For this use case, a random picking behavior
            for contributors has been developed. This mode only pays
            out to a few randomly picked contributors instead of all
            of them. Full split mode splits all funding. Possible values are:"""
                      )
        print("1: full_split")
        print("2: random_split")

        default = {
            "full_split": "1",
            "random_split": "2"
        }.get(defaultsDict.get("split_strategy"), "")

        answer = prompt(
            makeColorPrompt("split_strategy"),
            default=default,
            validator=IntegerValidator(min=1, max=2),
        )
        answer = [None, "full_split", "random_split"][int(answer)]
        answers["split_strategy"] = answer
        print("The split behavior has been set to " + answer)

        print("current bitcoin value: $%s (US)" % str(bitcoinPrice))
        print("you need %s BTC for $1 (US)" %
              str(Context(prec=6).divide(1, bitcoinPrice)))

        if answer == "random_split":
            printQuestion("How much should a picked contributor get?")
            answer = Decimal(
                prompt(
                    makeColorPrompt("random_split_btc_per_picked_contributor"),
                    default=str(
                        defaultsDict.get(
                            "random_split_btc_per_picked_contributor", "")),
                    validator=DecimalValidator(),
                ))
            print("Each picked contributor will receive %s BTC." % str(answer))
            print("Currently worth $%s (US)" % str(answer * bitcoinPrice))
            answers["random_split_btc_per_picked_contributor"] = answer

            printQuestion(
                "How many contributors should get picked at random picking?")
            answer = int(
                prompt(
                    makeColorPrompt("random_split_picked_contributors"),
                    default=str(
                        defaultsDict.get("random_split_picked_contributors",
                                         "")),
                    validator=IntegerValidator(),
                ))
            answers["random_split_picked_contributors"] = answer

        printQuestion("How much should be sent in each run of LibreSelery?")
        answer = Decimal(
            prompt(
                makeColorPrompt("payout_per_run"),
                default=str(defaultsDict.get("payout_per_run", "")),
                validator=DecimalValidator(),
            ))
        print("Each run of LibreSelery will send %s BTC" % str(answer))
        print("Currently worth $%s (US)" % str(answer * bitcoinPrice))
        answers["payout_per_run"] = answer

        printQuestion("What should be the minimum payment per contributor?")
        answer = Decimal(
            prompt(
                makeColorPrompt("min_payout_per_contributor"),
                default=str(defaultsDict.get("min_payout_per_contributor",
                                             "")),
                validator=DecimalValidator(),
            ))
        print("Currently worth %s$" % str(answer * bitcoinPrice))
        answers["min_payout_per_contributor"] = answer

        printQuestion(
            "How many commits should a contributor have at minimum to be picked as a contributor to receive compensation?"
        )
        answer = int(
            prompt(
                makeColorPrompt("min_contributions_required_payout"),
                default=str(
                    defaultsDict.get("min_contributions_required_payout", "")),
                validator=IntegerValidator(),
            ))
        answers["min_contributions_required_payout"] = answer

        printQuestion("What is the source Bitcoin address payout?")
        answer = prompt(
            makeColorPrompt("bitcoin_address"),
            default=str(defaultsDict.get("bitcoin_address", "")),
            validator=BitcoinAddressValidator(),
        )
        print("%s will be used to pay out contributors." % answer)
        answers["bitcoin_address"] = answer

        printQuestion(
            "Should LibreSelery validate that the public bitcoin address matches the secret coinbase address?"
        )
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("perform_wallet_validation"),
                default=str(defaultsDict.get("perform_wallet_validation", "")),
                validator=BoolValidator(),
            ))
        if answer:
            print("Double checking of bitcoin address enabled.")
        else:
            print("Double checking of bitcoin address disabled.")
        answers["perform_wallet_validation"] = answer

        printQuestion("Do you want Coinbase to send notification e-mails?")
        answer = answerStringToBool(
            prompt(
                makeColorPrompt("send_email_notification"),
                default=str(defaultsDict.get("send_email_notification", "")),
                validator=BoolValidator(),
            ))
        if answer:
            print("Email notifications will be sent.")
        else:
            print("Sending of notification emails is disabled.")
        answers["send_email_notification"] = answer

        if answer:
            printQuestion(
                "What message to you want to attach in each coinbase email?")
            answer = prompt(
                makeColorPrompt("optional_email_message"),
                default=str(defaultsDict.get("optional_email_message", "")),
            )
            if len(answer) > 0:
                print("message in notifications: " + answer)
                answers["optional_email_message"] = answer
            else:
                print("message in notifications disabled")

        return answers

    except KeyboardInterrupt:
        print("Setup canceled, nothing is safed.")
    except EOFError:
        print("EOF reached. nothing is safed.")
示例#14
0
    def __init__(self, **kwargs):
        bounty = kwargs['bounty']
        url = kwargs['url']
        user = kwargs['user']
        from_user = kwargs['from_user']
        notification_name = kwargs['notification_name']
        review = kwargs.get('review')
        comment = kwargs.get('comment')
        description = kwargs.get('fulfillment_description', '')
        preview_text = kwargs.get('string_data', '')

        if notification_name.__class__ != int:
            raise TypeError('notification_name must be of type int')
        elif notification_name not in Email.templates:
            raise ValueError(
                'notification_name {} must be a valid notification'.format(
                    notification_name))
        if bounty.__class__ != Bounty:
            raise TypeError('bounty must be of type Bounty')

        issuer = bounty.user

        token_decimals = Context(prec=6).create_decimal
        usd_decimals = Context(prec=3).create_decimal
        remaining = token_decimals(bounty.calculated_balance).normalize()
        token_amount = token_decimals(
            bounty.calculated_fulfillmentAmount).normalize()

        if len(description) > self.max_description_length:
            # Cut off at the closest word after the limit
            description = wrap(
                description,
                self.max_description_length
            )[0] + ' ...'

        title = bounty.title
        if len(title) > self.max_title_length:
            # Cut off at the closest word after the limit
            title = wrap(title, self.max_title_length)[0] + ' ...'

        if not url or len(url) == 0:
            url = bounty_url_for(bounty.bounty_id, bounty.platform)

        remaining_submissions = 0

        if notification_name == constants.BOUNTY_EXPIRED:
            remaining_submissions = Fulfillment.objects.filter(
                bounty_id=bounty.id,
                accepted=False,
            ).all().count()

        remaining_usd = ' unknown'
        if bounty.tokenLockPrice:
            remaining_usd = usd_decimals(
                remaining * usd_decimals(bounty.tokenLockPrice)).normalize()
        elif bounty.token and bounty.token.price_usd:
            remaining_usd = usd_decimals(
                remaining * usd_decimals(bounty.token.price_usd)).normalize()

        added_amount = 0
        if notification_name == constants.CONTRIBUTION_ADDED:
            inputs = kwargs['inputs']
            added_amount = token_decimals(calculate_token_value(
                int(inputs['value']), bounty.tokenDecimals)).normalize()

        rating_url = url
        if notification_name == constants.FULFILLMENT_ACCEPTED_FULFILLER:
            rating_url = '{}?fulfillment_id={}&rating=true'.format(
                url, kwargs['fulfillment_id'])

        self.__dict__.update({
            'bounty': bounty,
            'bounty_title': title,
            'url': url,
            'preferences_link': 'https://{}bounties.network/settings'.format(
                '' if ENVIRONMENT == 'production' else 'staging.'),
            'notification_name': notification_name,
            'usd_amount': usd_decimals(bounty.usd_price).normalize(),
            'token_amount': token_amount,
            'token': bounty.tokenSymbol,
            'bounty_categories': Email.render_categories(
                bounty.data_categories),
            'token_amount_remaining': remaining,
            'usd_amount_remaining': remaining_usd,
            'added_amount': added_amount,
            'remaining_submissions': remaining_submissions,
            'fulfillment_description': description,
            'issuer_name': issuer and issuer.name,
            'issuer_address': issuer and shorten_address(
                issuer.public_address),
            'issuer_profile_image': (
                issuer and issuer.profile_image or default_image
            ),
            'issuer_address_link': issuer and profile_url_for(
                issuer.public_address, bounty.platform),
            'user_name': user and user.name,
            'user_address': user and shorten_address(user.public_address),
            'user_profile_image': (
                user and user.profile_image or default_image
            ),
            'user_address_link': user and profile_url_for(
                user.public_address, bounty.platform),
            'from_user_name': from_user and from_user.name,
            'from_user_address': from_user and shorten_address(
                from_user.public_address),
            'from_user_profile_image': (
                from_user and from_user.profile_image or default_image
            ),
            'from_user_address_link': from_user and profile_url_for(
                from_user.public_address, bounty.platform),
            'from_user_email': from_user and from_user.email,
            'review': review and review.review,
            'rating': review and '{}/5'.format(review.rating),
            'rating_color': review and Email.rating_color(review.rating),
            'comment': comment and comment.text,
            'MC_PREVIEW_TEXT': preview_text,
            'rating_url': rating_url
        })
示例#15
0
def floatformat(text, arg=-1):
    """
    Display a float to a specified number of decimal places.

    If called without an argument, display the floating point number with one
    decimal place -- but only if there's a decimal place to be displayed:

    * num1 = 34.23234
    * num2 = 34.00000
    * num3 = 34.26000
    * {{ num1|floatformat }} displays "34.2"
    * {{ num2|floatformat }} displays "34"
    * {{ num3|floatformat }} displays "34.3"

    If arg is positive, always display exactly arg number of decimal places:

    * {{ num1|floatformat:3 }} displays "34.232"
    * {{ num2|floatformat:3 }} displays "34.000"
    * {{ num3|floatformat:3 }} displays "34.260"

    If arg is negative, display arg number of decimal places -- but only if
    there are places to be displayed:

    * {{ num1|floatformat:"-3" }} displays "34.232"
    * {{ num2|floatformat:"-3" }} displays "34"
    * {{ num3|floatformat:"-3" }} displays "34.260"

    If arg has the 'g' suffix, force the result to be grouped by the
    THOUSAND_SEPARATOR for the active locale. When the active locale is
    en (English):

    * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67"
    * {{ 10000|floatformat:"g" }} displays "10,000"

    If arg has the 'u' suffix, force the result to be unlocalized. When the
    active locale is pl (Polish):

    * {{ 66666.6666|floatformat:"2" }} displays "66666,67"
    * {{ 66666.6666|floatformat:"2u" }} displays "66666.67"

    If the input float is infinity or NaN, display the string representation
    of that value.
    """
    force_grouping = False
    use_l10n = True
    if isinstance(arg, str):
        last_char = arg[-1]
        if arg[-2:] in {"gu", "ug"}:
            force_grouping = True
            use_l10n = False
            arg = arg[:-2] or -1
        elif last_char == "g":
            force_grouping = True
            arg = arg[:-1] or -1
        elif last_char == "u":
            use_l10n = False
            arg = arg[:-1] or -1
    try:
        input_val = repr(text)
        d = Decimal(input_val)
    except InvalidOperation:
        try:
            d = Decimal(str(float(text)))
        except (ValueError, InvalidOperation, TypeError):
            return ""
    try:
        p = int(arg)
    except ValueError:
        return input_val

    try:
        m = int(d) - d
    except (ValueError, OverflowError, InvalidOperation):
        return input_val

    if not m and p < 0:
        return mark_safe(
            formats.number_format(
                "%d" % (int(d)),
                0,
                use_l10n=use_l10n,
                force_grouping=force_grouping,
            ))

    exp = Decimal(1).scaleb(-abs(p))
    # Set the precision high enough to avoid an exception (#15789).
    tupl = d.as_tuple()
    units = len(tupl[1])
    units += -tupl[2] if m else tupl[2]
    prec = abs(p) + units + 1

    # Avoid conversion to scientific notation by accessing `sign`, `digits`,
    # and `exponent` from Decimal.as_tuple() directly.
    rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec))
    sign, digits, exponent = rounded_d.as_tuple()
    digits = [str(digit) for digit in reversed(digits)]
    while len(digits) <= abs(exponent):
        digits.append("0")
    digits.insert(-exponent, ".")
    if sign and rounded_d:
        digits.append("-")
    number = "".join(reversed(digits))
    return mark_safe(
        formats.number_format(
            number,
            abs(p),
            use_l10n=use_l10n,
            force_grouping=force_grouping,
        ))
示例#16
0

# RESOLVE ISSUE First 10-digit prime in consecutive digits of e


from decimal import Context
import math

original = str(Context(prec=300).exp(1)) 
print(original)

count =2
while True:
    tempTen = int(original[count:count+10]) 
    if tempTen%6==1 or tempTen%6==5:
        currentHigh = abs(int(math.sqrt(tempTen)))
        for i in range(2, currentHigh+1):
            if tempTen%i==0:  
                count = count+1
                break 
            elif i!=currentHigh:
                continue
            else:
                print("this is our number", tempTen)
                exit()              
    else:
        count = count+1
示例#17
0
    arr_p = arr_p / 5.0
    arr_r = arr_r / 5.0
    arr_f1 = arr_f1 / 5.0
    arr_auc = arr_auc / 5.0

    stats_P1 = Stats.Stats(P1_value)
    stats_R1 = Stats.Stats(R1_value)
    stats_F11 = Stats.Stats(F11_value)
    stats_AUC1 = Stats.Stats(AUC1_value)
    print "P1_value:", P1_value
    print "R1_value:", R1_value
    print "F11_value:", F11_value
    print "AUC1_value:", AUC1_value
    print 'stats_P1(mean value ± standard deviation): %.2f±%.2f' % (Decimal(
        str(stats_P1.avg())).normalize(Context(
            prec=3, rounding=ROUND_HALF_UP)), Decimal(str(
                stats_P1.stdev())).normalize(
                    Context(prec=3, rounding=ROUND_HALF_UP)))
    print 'stats_R1(mean value ± standard deviation): %.2f±%.2f' % (Decimal(
        str(stats_R1.avg())).normalize(Context(
            prec=3, rounding=ROUND_HALF_UP)), Decimal(str(
                stats_R1.stdev())).normalize(
                    Context(prec=3, rounding=ROUND_HALF_UP)))
    print 'stats_F11(mean value ± standard deviation): %.2f±%.2f' % (Decimal(
        str(stats_F11.avg())).normalize(Context(
            prec=3, rounding=ROUND_HALF_UP)), Decimal(str(
                stats_F11.stdev())).normalize(
                    Context(prec=3, rounding=ROUND_HALF_UP)))
    print 'stats_AUC1(mean value ± standard deviation): %.2f±%.2f' % (
        Decimal(str(stats_AUC1.avg())).normalize(
            Context(prec=3, rounding=ROUND_HALF_UP)),
示例#18
0
from decimal import Decimal, Context
from mod import terminal
from mod import func2
import decimal
import time
import math
import sys
import os

install_terminaltables = terminal.status_table()
install_termcolor = terminal.status_color()

statistic = Statistic()
process = Process()
mod = ModoAudit(process)
math_decimal = Context()

modo_agrupados = None

modo_1 = "Modo Dados Brutos"
modo_2 = "Modo Dados Agrupados"

#Menu Principal
commands1 = ["[1] - Dados Brutos",\
        "[2] - Dados Agrupados",\
        "[3] - Sobre",\
        "[4] - Informações",\
        "[5] - Configurações",\
           "[6] - Sair"]

#Menu Dados Agrupados
示例#19
0
文件: calcs.py 项目: Satook/paycalc
from decimal import Decimal, Context, ROUND_HALF_UP, localcontext

# We will use this context when performing calculations
decimal_context = Context(prec=28, rounding=ROUND_HALF_UP)


def round_to_dollar(dec):
    '''
    Rounds `dec` to the nearest whole dollar. Rounding up when cents > 50,
    otherwise down.

    :param dec: A decimal.Decimal value to round.
    :returns: A decimal.Decimal
    '''

    with localcontext(decimal_context):
        return round(dec, 0)


def calc_gross_income(annual_income):
    '''
    Calculate the gross income for the month.

    :param annual_income: Their annual income
    :returns: The months gross income rounded to the dollar
    '''
    return round_to_dollar(annual_income / Decimal(12))


def calc_super_contrib(income, rate):
    '''
示例#20
0
# Hardcode Supported Markets
from decimal import Decimal, Context
from functools import partial

from oracle_voter.markets import pricing
from oracle_voter.feeds import coinone, ukfx

WEI_VALUE = Decimal("10.0") ** -18

ABSTAIN_VOTE_PX = Decimal("-1.00").quantize(
    WEI_VALUE,
    context=Context(prec=40),
)

# Feed Sources
exchange_coinone = coinone.Coinone("https://api.coinone.co.kr")

feed_ukfx = ukfx.UKFX("https://api.ukfx.co.uk")

class ExchangeErr(Exception):
    def __init__(self, message, err):
        super().__init__(message)
        self.exchange_err = err


async def fetch_coinone_krw():
    currency = "LUNA"
    err, orderbook = await exchange_coinone.get_orderbook(currency)
    # Get MicroPrice
    if err is not None:
        raise ExchangeErr(f"Exchange Coinone threw error", err)
示例#21
0
def test_context_init():
    context = Context(prec=5)
    field = fields.DecimalField(context=context)
    assert isinstance(field.context, Context)
    assert field.context == context
示例#22
0
async def derive_rate(target):
    base_currency = "krw"
    raw_px = await feed_ukfx.get_swap(base_currency, target)
    return Decimal(raw_px).quantize(WEI_VALUE, context=Context(prec=40))
示例#23
0
class Credit:
    # setup
    myothercontext = Context(prec=12)
    setcontext(myothercontext)

    # ad-hoc constant
    Neutral = Decimal(1)
    Annual_fix = Decimal(365 / 360)
    Nper_in_a_year = Decimal(1 / 12)
    Periods = Decimal(12)
    fire_insurance_rate = Decimal(0.00168)
    life_insurance_rate = Decimal(0.000068)
    monthly_fix = 3
    credit_property_insurance_factor = {
        "dpto": Decimal(0.9),
        "casa": Decimal(0.75),
    }

    def __init__(self, property_value, loan, nper, interest, grace,
                 property_type):
        self.property_value = property_value
        self.property_type = property_type
        self.loan = Decimal(loan)
        self.nper = nper
        self.fire_kapital = self.get_fire_kapital
        self.fire_insurance_factor = self.get_fire_insurance_factor
        self.interest = interest
        self.grace = grace
        self.monthly_interest = self.get_monthly_interest
        self.initial_k = self.get_initial_k
        self.factor = self.get_factor
        self.payment = self.get_payment
        self.build_development = self.build_development_list

    @staticmethod
    def thirdpow(a, b, c):
        return pow(
            pow(a, b), c
        )  # Excel does a ^ b ^ c as [(a ^ b) ^ c] instead of [a ^ (b ^ c)]

    @property
    def get_monthly_interest(self):
        return self.thirdpow(self.Neutral + self.interest, self.Annual_fix,
                             self.Nper_in_a_year) - self.Neutral

    @property
    def get_initial_k(self):
        kapital = self.loan
        for x in range(self.grace):
            kapital += round(kapital * self.monthly_interest, 4)
        return kapital

    @property
    def get_factor(self):
        return self.monthly_interest / (
            self.Neutral -
            (pow(self.monthly_interest + self.Neutral, self.nper * -1)))

    @property
    def get_payment(self):
        return round(self.factor * self.initial_k, 4)

    @property
    def get_fire_kapital(self):
        return self.property_value * self.credit_property_insurance_factor[
            self.property_type]

    @property
    def get_fire_insurance_factor(self):
        return self.fire_kapital * self.fire_insurance_rate / self.Periods
示例#24
0
from decimal import ROUND_HALF_UP, Context
import tensorflow as tf
from sklearn.metrics import f1_score, precision_score, recall_score

rounder = Context(rounding=ROUND_HALF_UP, prec=4)


def accuracy(y_pred, y_true):
    # Predicted class is the index of highest score in prediction vector (i.e. argmax).
    correct_prediction = tf.equal(tf.argmax(y_pred, 1),
                                  tf.cast(y_true, tf.int64))
    return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1)


def F1(y_pred, y_true):
    y_pred = tf.argmax(y_pred, 1).numpy()
    return rounder.create_decimal_from_float(
        f1_score(y_true, y_pred, average="micro"))


def precision(y_pred, y_true):
    y_pred = tf.argmax(y_pred, 1).numpy()
    return rounder.create_decimal_from_float(
        precision_score(y_true, y_pred, average="micro"))


def recall(y_pred, y_true):
    y_pred = tf.argmax(y_pred, 1).numpy()
    return rounder.create_decimal_from_float(
        recall_score(y_true, y_pred, average="micro"))
示例#25
0
文件: types.py 项目: jspreddy/dynamo3
from .constants import (
    BINARY,
    BINARY_SET,
    BOOL,
    LIST,
    MAP,
    NULL,
    NUMBER,
    NUMBER_SET,
    STRING,
    STRING_SET,
)

DECIMAL_CONTEXT = Context(Emin=-128,
                          Emax=126,
                          rounding=None,
                          prec=38,
                          traps=[Clamped, Overflow, Underflow])

# Dynamo values after we have encoded them
DynamoNumber = TypedDict("DynamoNumber", {"N": Decimal})
DynamoString = TypedDict("DynamoString", {"S": str})
DynamoBinary = TypedDict("DynamoBinary", {"B": "Binary"})
DynamoSetNumber = TypedDict("DynamoSetNumber", {"NS": List[Decimal]})
DynamoSetString = TypedDict("DynamoSetString", {"SS": List[str]})
DynamoSetBinary = TypedDict("DynamoSetBinary", {"BS": List["Binary"]})
DynamoList = TypedDict(
    "DynamoList",
    {"L": List[Any]}  # mypy doesn't support recursion yet
)
DynamoBool = TypedDict("DynamoBool", {"BOOL": bool})
示例#26
0
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
"""
Some utility functions to deal with mapping Amazon DynamoDB types to
Python types and vice-versa.
"""
import base64
from decimal import (Decimal, DecimalException, Context, Clamped, Overflow,
                     Inexact, Underflow, Rounded)
from boto.dynamodb.exceptions import DynamoDBNumberError
from boto.compat import filter, map, six, long_type

DYNAMODB_CONTEXT = Context(
    Emin=-128,
    Emax=126,
    rounding=None,
    prec=38,
    traps=[Clamped, Overflow, Inexact, Rounded, Underflow])


# python2.6 cannot convert floats directly to
# Decimals.  This is taken from:
# http://docs.python.org/release/2.6.7/library/decimal.html#decimal-faq
def float_to_decimal(f):
    n, d = f.as_integer_ratio()
    numerator, denominator = Decimal(n), Decimal(d)
    ctx = DYNAMODB_CONTEXT
    result = ctx.divide(numerator, denominator)
    while ctx.flags[Inexact]:
        ctx.flags[Inexact] = False
        ctx.prec *= 2
示例#27
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
示例#28
0
def formatNumber(number, *, precision=2):
    c = Context(prec=precision)
    n = c.create_decimal_from_float(number)
    return n.to_eng_string(context=c)
示例#29
0
def floatformat(text, arg=-1):
    """
    Displays a float to a specified number of decimal places.

    If called without an argument, it displays the floating point number with
    one decimal place -- but only if there's a decimal place to be displayed:

    * num1 = 34.23234
    * num2 = 34.00000
    * num3 = 34.26000
    * {{ num1|floatformat }} displays "34.2"
    * {{ num2|floatformat }} displays "34"
    * {{ num3|floatformat }} displays "34.3"

    If arg is positive, it will always display exactly arg number of decimal
    places:

    * {{ num1|floatformat:3 }} displays "34.232"
    * {{ num2|floatformat:3 }} displays "34.000"
    * {{ num3|floatformat:3 }} displays "34.260"

    If arg is negative, it will display arg number of decimal places -- but
    only if there are places to be displayed:

    * {{ num1|floatformat:"-3" }} displays "34.232"
    * {{ num2|floatformat:"-3" }} displays "34"
    * {{ num3|floatformat:"-3" }} displays "34.260"

    If the input float is infinity or NaN, the (platform-dependent) string
    representation of that value will be displayed.
    """

    try:
        input_val = repr(text)
        d = Decimal(input_val)
    except UnicodeEncodeError:
        return ''
    except InvalidOperation:
        if input_val in special_floats:
            return input_val
        try:
            d = Decimal(force_text(float(text)))
        except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError):
            return ''
    try:
        p = int(arg)
    except ValueError:
        return input_val

    try:
        m = int(d) - d
    except (ValueError, OverflowError, InvalidOperation):
        return input_val

    if not m and p < 0:
        return mark_safe(formats.number_format('%d' % (int(d)), 0))

    if p == 0:
        exp = Decimal(1)
    else:
        exp = Decimal('1.0') / (Decimal(10)**abs(p))
    try:
        # Set the precision high enough to avoid an exception, see #15789.
        tupl = d.as_tuple()
        units = len(tupl[1])
        units += -tupl[2] if m else tupl[2]
        prec = abs(p) + units + 1

        # Avoid conversion to scientific notation by accessing `sign`, `digits`
        # and `exponent` from `Decimal.as_tuple()` directly.
        sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP,
                                            Context(prec=prec)).as_tuple()
        digits = [six.text_type(digit) for digit in reversed(digits)]
        while len(digits) <= abs(exponent):
            digits.append('0')
        digits.insert(-exponent, '.')
        if sign:
            digits.append('-')
        number = ''.join(reversed(digits))
        return mark_safe(formats.number_format(number, abs(p)))
    except InvalidOperation:
        return input_val
示例#30
0
class labfloat:
    """Represents a gaussian distribution.

    A labfloat object stores an gaussian's distribuition mean and standard deviation, in
    witch can be used to represent a experimental physical measure. Therefore, all
    arithmetics calculations done with this object will properlly propagate it's error
    analytically in accordance with the gaussian propagation formula. Furthermore, the
    comparison methods are also using the statistical relation testing equations.

    If one or more list is passed as an argument, it will call labfloat.list()
    to convert the nested list and return the nested list of labfloats. Or else,
    it will create an single instance of labfloat.

    Raises:
        LabFloatError: Labfloat Generic error due to missused interface.

    """

    context = Context(rounding=ROUND_HALF_UP)
    """Context: Set ROUND_HALF_UP for the decimals used in __round__ method."""

    def __new__(cls, *args, **kwargs) -> Union[object, Iterable]:
        """Create an instance of labfloat or a nested list of labfloat.

        If one or more list is passed as an argument, it will call labfloat.list()
        to convert the nested list and return the nested list of labfloats. Or else,
        it will create an single instance of labfloat.

        Raises:
            LabFloatError: Missing errors or means list to convert nested list.

        Returns:
            Union[object, Iterable]: Nested list of labfloat or a new labfloat object.

        Examples:
            >>> labfloat(1,3)
            >>> labfloat([1,2,3,4],[1,1,1,1])
            >>> labfloat([15,16,17,18],[10,10,10,10],[16,17,18,19],[10,10,10,10])

        """
        listlabfloat = kwargs.get("list", [])
        if args:
            if isinstance(args[0], Iterable):
                listlabfloat = args
        if listlabfloat != []:
            if len(listlabfloat) % 2 != 0:
                raise LabFloatError(3, listlabfloat)
            return cls.list(listlabfloat)

        return object.__new__(cls)

    def __init__(self, *args, **kwargs):
        """Create an instance of labfloat or a nested list of labfloat.

        If one or more list is passed as an argument, it will call labfloat.list()
        to convert the nested list and return the nested list of labfloats. Or else,
        it will create an single instance of labfloat.

        Raises:
            LabFloatError: Missing errors or means list to convert nested list.
            LabFloatError: Too many arguments.

        Returns:
            Union[object, Iterable]: Nested list of labfloat or a new labfloat object.

        Examples:
            >>> labfloat(1,3)
            >>> labfloat([1,2,3,4],[1,1,1,1])
            >>> labfloat([15,16,17,18],[10,10,10,10],[16,17,18,19],[10,10,10,10])

        """
        # NOTE: docstring the same as __new__ method due to editor only showing __init__ docstring.
        mean = kwargs.get("mean", 0.0)
        uncertainty = kwargs.get("uncertainty", 0.0)

        if args:
            if len(args) == 1:
                mean = args[0]
            elif len(args) == 2:
                mean = args[0]
                uncertainty = args[1]
            elif len(args) > 2:
                raise LabFloatError(1, args)

        self._mean = mean
        self._uncertainty = abs(uncertainty)

    @classmethod
    def list(cls, listargs: Iterable) -> Iterable:
        """Convert nested list of means and errors to nested list of labfloat.

        Args:
            listargs (Iterable): Nested list of means and list of erros.

        Raises:
            LabFloatError: Means list and erros list does not have the same length.

        Returns:
            Iterable: Nested list of labfloats.

        """
        listlabfloat = []
        for j in range(0, len(listargs), 2):
            if len(listargs[j]) == len(listargs[j + 1]):
                colum = []
                for k in range(len(listargs[j])):
                    colum += [cls(listargs[j][k], listargs[j + 1][k])]
                listlabfloat += [colum]
            else:
                raise LabFloatError(2, listargs[j], listargs[j + 1])
        if len(listlabfloat) == 1:
            listlabfloat = listlabfloat[0]
        return listlabfloat

    def __round__(self, p: int = 0) -> labfloat:
        """Round labfloat's mean and uncertainty at p decimal places.

        When no arguments are passed or p=0, the mean and uncertainty will round at the
        uncertainty most significant figure to nearest with ties going away from zero
        (Round half away from zero) using Python's ROUND_HALF_UP. If a value is passe to
        p it will round at p decimal places, and if p is greater than the error's most
        significant figure decimal place, the error will be one at the mean's least
        significant figure decimal place.

        Args:
            p (int, optional): The number of decimals to use when rounding. Defaults to 0.

        Returns:
            labfloat: New labfloat with the rounded mean and error.

        """
        current_contex = getcontext()
        setcontext(self.context)

        u = Decimal(str(self._uncertainty))
        m = Decimal(str(self._mean))

        r = p - u.adjusted() * (not p)

        u = round(u, r)

        r = p - u.adjusted() * (not p)

        u += Decimal("1e{}".format(-r)) * (not u)

        m = round(m, r)

        setcontext(current_contex)

        return labfloat(type(self._mean)(m), type(self._uncertainty)(u))

    def split(self) -> List[str]:
        """Split the string representation of labfloat.

        The split is done in the ± keyword.

        Returns:
            List[str]: rounded labfloat's mean and error in str format.

        """
        m, u = self.__round__()
        return ["{:g}".format(m), "{:g}".format(u)]

    def tex(
        self, precision: Union[Tuple[float], float] = None, round_p: int = 0
    ) -> str:
        """Convert labfloat to string representation in LaTex format.

        The arguments precision and round_p are used to configure the display precision and round
        decimal places. The precision is a float in "0.0" format.

        Args:
            precision (Union[Tuple[float], float], optional): A tuple containing the mean's and error's precision or only one string for both precisions. If no value are passed the default precision. Defaults to None.
            round_p (int, optional): Number of decimals to use when rounding. Defaults to 0.

        Raises:
            LabFloatError: Error in parsing arguments, where the number of precision tuple is greater than 2.

        Returns:
            str: labfloat's strig representation in LaTex format.

        """
        if isinstance(precision, tuple):
            if len(precision) > 2:
                raise LabFloatError(4, precision)
            precision = (float(precision[0]), float(precision[1]))
        elif precision:
            precision = (float(precision), float(precision))

        if self._uncertainty == 0:
            if precision:
                precision[0] = str(precision[0])
                m = eval("'{:." + precision[0] + "e}'.format(self._mean)")
            else:
                m = self.split()[0]
            m = m.split("e")
            if len(m) > 1:
                m = m[0] + r"\cdot 10^{" + m[1] + "}"
            else:
                m = m[0]
            return "{0}".format(m)

        if precision:
            m, u = self.__round__(round_p)
            precision = (str(precision[0]), str(precision[1]))
            m = eval("'{:." + precision[0] + "e}'.format(m)")
            u = eval("'{:." + precision[1] + "e}'.format(u)")
        else:
            m, u = self.split()
        m = m.split("e")
        u = u.split("e")
        if len(m) > 1:
            m = m[0] + r"\cdot 10^{" + m[1] + "}"
        else:
            m = m[0]
        if len(u) > 1:
            u = u[0] + r"\cdot 10^{" + u[1] + "}"
        else:
            u = u[0]
        return r"({0}\, \pm \,{1})".format(m, u)

    def __str__(self) -> str:
        """Convert the labfloat to it's string representation.

        For conventional displaying pourposes the lablofat will be rouded using the
        default method.

        Returns:
            str: gaussian distribuiton mean and error string representation.

        """
        return "({0} ± {1})".format(*self.split())

    def __repr__(self) -> str:
        """Represent labfloat as a string object.

        Returns:
            str: labfloat's string convertion.

        """
        return self.__str__()

    @property
    def mean(self) -> object:
        """object: labfloat's mean."""
        return self._mean

    @property
    def uncertainty(self) -> object:
        """object: labfloat's error."""
        return self._uncertainty

    def __getitem__(self, idx: int) -> Tuple[object]:
        """Represent the labfloat as an tuple.

        This method indexes the labfloat's attributes mean and erro as an tuple object.
        Therefore, with this magic method labfloat can be used as an tuple.

        Args:
            idx (int): idex position of the labfis tuple representation

        Returns:
            Tuple[object]: A tuple with labfloat's mean and error.

        Example:
            >>> a, b = labfloat(1,3)
            >>> print(*labfloat(1,3))
            >>> for i in labfloat(1,3): print(i)

        """
        vals = (self.mean, self.uncertainty)
        return vals[idx]

    def __pos__(self) -> labfloat:
        return self

    def __neg__(self) -> labfloat:
        return labfloat(-self._mean, self._uncertainty)

    def __abs__(self) -> labfloat:
        return labfloat(abs(self._mean), self._uncertainty)

    def __floor__(self) -> labfloat:
        return labfloat(floor(self._mean), floor(self._uncertainty))

    def __ceil__(self) -> labfloat:
        return labfloat(ceil(self._mean), ceil(self._uncertainty))

    def __trunc__(self) -> labfloat:
        return labfloat(trunc(self._mean), trunc(self._uncertainty))

    def __eq__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return abs(self._mean - other.mean) < 2 * (
                self._uncertainty + other.uncertainty
            )
        if isinstance(other, Number):
            return abs(self._mean - other) < 2 * self._uncertainty

        return None

    def __ne__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return abs(self._mean - other.mean) > 3 * (
                self._uncertainty + other.uncertainty
            )
        if isinstance(other, Number):
            return abs(self._mean - other) > 3 * self._uncertainty

        return None

    def __lt__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return self._mean + self._uncertainty < other.mean - other.uncertainty
        if isinstance(other, Number):
            return self._mean + self._uncertainty < other

        return None

    def __gt__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return self._mean - self._uncertainty > other.mean + other.uncertainty
        if isinstance(other, Number):
            return self._mean - self._uncertainty > other

        return None

    def __le__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return self._mean + self._uncertainty <= other.mean + other.uncertainty
        if isinstance(other, Number):
            return self._mean + self._uncertainty <= other

        return None

    def __ge__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return self._mean - self._uncertainty >= other.mean - other.uncertainty
        if isinstance(other, Number):
            return self._mean - self._uncertainty >= other

        return None

    def __add__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                self._mean + other.mean,
                (self._uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(self._mean + other, self._uncertainty)

        return None

    def __radd__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__add__(other)

    def __iadd__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__add__(other)

    def __sub__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                self._mean - other.mean,
                (self._uncertainty ** 2 + other.uncertainty ** 2) ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(self._mean - other, self._uncertainty)

        return None

    def __rsub__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                other.mean - self._mean,
                (other.uncertainty ** 2 + self._uncertainty ** 2) ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(other - self._mean, self._uncertainty)

        return None

    def __isub__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__sub__(other)

    def __mul__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                self._mean * other.mean,
                (
                    (other.mean * self._uncertainty) ** 2
                    + (self._mean * other.uncertainty) ** 2
                )
                ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(self._mean * other, abs(other * self._uncertainty))

        return None

    def __rmul__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__mul__(other)

    def __imul__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__mul__(other)

    def __div__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                self._mean / other.mean,
                (
                    (self._uncertainty / other.mean) ** 2
                    + (self._mean * other.uncertainty / (other.mean ** 2)) ** 2
                )
                ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(self._mean / other, abs(self._uncertainty / other))

        return None

    def __truediv__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__div__(other)

    def __idiv__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__div__(other)

    def __itruediv__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__div__(other)

    def __rdiv__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                other.mean / self._mean,
                (
                    (other.uncertainty / self._mean) ** 2
                    + (other.mean * self._uncertainty / (self._mean ** 2)) ** 2
                )
                ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(
                other / self._mean, abs(other * self._uncertainty / self._mean ** 2)
            )

        return None

    def __rtruediv__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__rdiv__(other)

    def __pow__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                self._mean ** other.mean,
                (
                    (other.mean * self._mean ** (other.mean - 1) * self._uncertainty)
                    ** 2
                    + (
                        self._mean ** other.mean
                        * log(abs(self._mean))
                        * other.uncertainty
                    )
                    ** 2
                )
                ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(
                self._mean ** other,
                abs(other * self._mean ** (other - 1) * self._uncertainty),
            )

        return None

    def __rpow__(self, other: Union[labfloat, Number]) -> labfloat:
        if isinstance(other, labfloat):
            return labfloat(
                other.mean ** self._mean,
                (
                    (self._mean * other.mean ** (self._mean - 1) * other.uncertainty)
                    ** 2
                    + (
                        other.mean ** self._mean
                        * log(abs(other.mean))
                        * self._uncertainty
                    )
                    ** 2
                )
                ** 0.5,
            )
        if isinstance(other, Number):
            return labfloat(
                other ** self._mean,
                abs(other ** self._mean * log(abs(other)) * self._uncertainty),
            )

        return None

    def __ipow__(self, other: Union[labfloat, Number]) -> labfloat:
        return self.__pow__(other)

    def sqrt(self) -> labfloat:
        return self.__pow__(0.5)

    def cos(self) -> labfloat:
        return labfloat(cos(self._mean), abs(-(sin(self._mean)) * self._uncertainty))

    def sin(self) -> labfloat:
        return labfloat(sin(self._mean), abs(cos(self._mean) * self._uncertainty))

    def tan(self) -> labfloat:
        return labfloat(
            tan(self._mean), ((cos(self._mean) ** -4) * self._uncertainty ** 2) ** 0.5
        )

    def arcsin(self) -> labfloat:
        return labfloat(asin(self._mean), self._uncertainty / (1 - self._mean ** 2))

    def arccos(self) -> labfloat:
        return labfloat(
            acos(self._mean), abs(-self._uncertainty / (1 - self._mean ** 2)) ** 0.5
        )

    def arctan(self) -> labfloat:
        return labfloat(atan(self._mean), self._uncertainty / (1 + self._mean ** 2))

    def __int__(self) -> int:
        return int(self._mean)

    def __float__(self) -> float:
        return float(self._mean)

    def __complex__(self) -> complex:
        return complex(self._mean)

    def __oct__(self) -> oct:
        return oct(self._mean)

    def __hex__(self) -> hex:
        return hex(self._mean)