当前位置: 首页>>代码示例>>Python>>正文


Python Decimal.from_float方法代码示例

本文整理汇总了Python中decimal.Decimal.from_float方法的典型用法代码示例。如果您正苦于以下问题:Python Decimal.from_float方法的具体用法?Python Decimal.from_float怎么用?Python Decimal.from_float使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在decimal.Decimal的用法示例。


在下文中一共展示了Decimal.from_float方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: round

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def round(number, ndigits=None):
        return_int = False
        if ndigits is None:
            return_int = True
            ndigits = 0
        if hasattr(number, '__round__'):
            return number.__round__(ndigits)

        if ndigits < 0:
            raise NotImplementedError('negative ndigits not supported yet')
        exponent = Decimal('10') ** (-ndigits)
        d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        if return_int:
            return int(d)
        else:
            return float(d) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:19,代码来源:pie_slice.py

示例2: get_bin_decimals

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def get_bin_decimals(v, max_sample=100, default=3):
    v = v.astype(float, raise_on_error=False)
    if len(v) <= max_sample:
        sample = v
    else:
        sample = random.sample(v, max_sample)

    num_decimals = []
    for e in sample:
        # num_decimals.append(str(e).find('.'))
        num_decimals.append(Decimal.from_float(e).as_tuple().exponent * -1)
    try:
        max_decimals = max(num_decimals)
    except:
        return default

    return min((max_decimals + 1), default) 
开发者ID:MacroConnections,项目名称:DIVE-backend,代码行数:19,代码来源:binning.py

示例3: test_binary_floats

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def test_binary_floats(self):
        # check that floats hash equal to corresponding Fractions and Decimals

        # floats that are distinct but numerically equal should hash the same
        self.check_equal_hash(0.0, -0.0)

        # zeros
        self.check_equal_hash(0.0, D(0))
        self.check_equal_hash(-0.0, D(0))
        self.check_equal_hash(-0.0, D('-0.0'))
        self.check_equal_hash(0.0, F(0))

        # infinities and nans
        self.check_equal_hash(float('inf'), D('inf'))
        self.check_equal_hash(float('-inf'), D('-inf'))

        for _ in range(1000):
            x = random.random() * math.exp(random.random()*200.0 - 100.0)
            self.check_equal_hash(x, D.from_float(x))
            self.check_equal_hash(x, F.from_float(x)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_numeric_tower.py

示例4: decimal

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def decimal(data):
        try:
            return dec_con.create_decimal(data).quantize(convert_to._quantizer)
        except TypeError:
            if isinstance(data, np.ndarray):
                return convert_to._quantize_array(data.astype(str))
            else:
                return Decimal.from_float(np.float64(data)).quantize(convert_to._quantizer)
        except InvalidOperation:
            if abs(data) > Decimal('1e20'):
                raise InvalidOperation("Numeric overflow in convert_to.decimal")
            elif data == np.nan or math.nan:
                raise InvalidOperation("NaN encountered in convert_to.decimal")
        except Exception as e:
            print(data)
            print(e)
            raise e


# ZMQ sockets helpers 
开发者ID:naripok,项目名称:cryptotrader,代码行数:22,代码来源:utils.py

示例5: test_convert_to

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def test_convert_to(data):
    if abs(data) < Decimal('1e18'):
        number = convert_to.decimal(data)
        assert number - Decimal.from_float(data).quantize(Decimal('0e-9')) < Decimal("1e-8")

    elif abs(data) < Decimal('1e33'):
        with pytest.raises(InvalidOperation):
            convert_to.decimal(data)
    else:
        with pytest.raises(Overflow):
            convert_to.decimal(data) 
开发者ID:naripok,项目名称:cryptotrader,代码行数:13,代码来源:test_utils.py

示例6: decimal_number

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def decimal_number(self, start: float = -1000.0,
                       end: float = 1000.0) -> Decimal:
        """Generate random decimal number.

        :param start:  Start range.
        :param end: End range.
        :return: Decimal object.
        """
        return Decimal.from_float(self.float_number(start, end)) 
开发者ID:lk-geimfari,项目名称:mimesis,代码行数:11,代码来源:numbers.py

示例7: upgrade

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def upgrade():
    op.add_column('request',
            sa.Column('numeric_base_payout', sa.Numeric(precision=15, scale=2),
                    default=0.0)
    )
    request = table('request',
            column('id', sa.Integer),
            column('base_payout', sa.Float),
            column('numeric_base_payout', sa.Numeric(precision=15, scale=2)),
    )
    conn = op.get_bind()
    requests_sel = select([request.c.id, request.c.base_payout])
    requests = conn.execute(requests_sel)
    for request_id, float_payout in requests:
        decimal_payout = Decimal.from_float(float_payout)
        decimal_payout *= 1000000
        update_stmt = update(request)\
                .where(request.c.id == request_id)\
                .values({
                    'numeric_base_payout': decimal_payout,
                })
        conn.execute(update_stmt)
    requests.close()
    op.drop_column('request', 'base_payout')
    op.alter_column('request',
            column_name='numeric_base_payout',
            new_column_name='base_payout',
            existing_type=sa.Numeric(precision=15, scale=2),
            existing_server_default=0.0) 
开发者ID:paxswill,项目名称:evesrp,代码行数:31,代码来源:4198a248c8a_.py

示例8: _convert_bounds_type

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def _convert_bounds_type(cls, value):
        return Decimal.from_float(float(value)) 
开发者ID:gltn,项目名称:stdm,代码行数:4,代码来源:config_serializer.py

示例9: newround

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.
 
    Delegates to the __round__ method if for some reason this exists.
 
    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.
 
    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)
    
    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)
 

### From Python 2.7's decimal.py. Only needed to support Py2.6: 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:44,代码来源:newround.py

示例10: from_float_26

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def from_float_26(f):
    """Converts a float to a decimal number, exactly.

    Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
    Since 0.1 is not exactly representable in binary floating point, the
    value is stored as the nearest representable value which is
    0x1.999999999999ap-4.  The exact equivalent of the value in decimal
    is 0.1000000000000000055511151231257827021181583404541015625.

    >>> Decimal.from_float(0.1)
    Decimal('0.1000000000000000055511151231257827021181583404541015625')
    >>> Decimal.from_float(float('nan'))
    Decimal('NaN')
    >>> Decimal.from_float(float('inf'))
    Decimal('Infinity')
    >>> Decimal.from_float(-float('inf'))
    Decimal('-Infinity')
    >>> Decimal.from_float(-0.0)
    Decimal('-0')

    """
    import math as _math
    from decimal import _dec_from_triple    # only available on Py2.6 and Py2.7 (not 3.3)

    if isinstance(f, (int, long)):        # handle integer inputs
        return Decimal(f)
    if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
        return Decimal(repr(f))
    if _math.copysign(1.0, f) == 1.0:
        sign = 0
    else:
        sign = 1
    n, d = abs(f).as_integer_ratio()
    # int.bit_length() method doesn't exist on Py2.6:
    def bit_length(d):
        if d != 0:
            return len(bin(abs(d))) - 2
        else:
            return 0
    k = bit_length(d) - 1
    result = _dec_from_triple(sign, str(n*5**k), -k)
    return result 
开发者ID:Soft8Soft,项目名称:verge3d-blender-addon,代码行数:44,代码来源:newround.py

示例11: newround

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if not PY26:
        d = Decimal.from_float(number).quantize(exponent,
                                            rounding=ROUND_HALF_EVEN)
    else:
        d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
开发者ID:remg427,项目名称:misp42splunk,代码行数:44,代码来源:newround.py

示例12: upgrade

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def upgrade():
    # Add discriminator column
    op.add_column('modifier', sa.Column('_type', sa.String(length=20)))
    # Create new subclass tables
    op.create_table('absolute_modifier',
            sa.Column('id', sa.Integer,
                    sa.ForeignKey('modifier.id'),
                    primary_key=True),
            sa.Column('value', sa.Numeric(precision=15, scale=2),
                    nullable=False, server_default='0.0'))
    op.create_table('relative_modifier',
            sa.Column('id', sa.Integer, sa.ForeignKey('modifier.id'),
                    primary_key=True),
            sa.Column('value', sa.Float, nullable=False, server_default='0.0'))
    # Add new entries to the subclass tables for each modifier
    conn = op.get_bind()
    modifier_sel = select([modifier.c.id, modifier.c.value, modifier.c.type_])
    modifiers = conn.execute(modifier_sel)
    absolutes = []
    relatives = []
    for modifier_id, modifier_value, modifier_type in modifiers:
        if modifier_type == 'absolute':
            discriminator = 'AbsoluteModifier'
            absolutes.append({
                    'id': modifier_id,
                    'value': Decimal.from_float(modifier_value) * 1000000,
            })
        elif modifier_type == 'percentage':
            discriminator = 'RelativeModifier'
            relatives.append({
                    'id': modifier_id,
                    'value': modifier_value / 100,
            })
        update_stmt = update(modifier)\
                .where(modifier.c.id == modifier_id)\
                .values({
                        '_type': discriminator,
                })
        conn.execute(update_stmt)
    modifiers.close()
    op.bulk_insert(abs_table, absolutes)
    op.bulk_insert(rel_table, relatives)
    # Drop the old value and type_ columns from modifier
    op.drop_column('modifier', 'value')
    op.drop_column('modifier', 'type_')
    # Add the not-null constraint to the _type column
    op.alter_column('modifier',
            column_name='_type',
            nullable=True,
            existing_type=sa.String(length=20),
    ) 
开发者ID:paxswill,项目名称:evesrp,代码行数:53,代码来源:2976d59f286_.py

示例13: newround

# 需要导入模块: from decimal import Decimal [as 别名]
# 或者: from decimal.Decimal import from_float [as 别名]
def newround(number, ndigits=None):
    """
    See Python 3 documentation: uses Banker's Rounding.

    Delegates to the __round__ method if for some reason this exists.

    If not, rounds a number to a given precision in decimal digits (default
    0 digits). This returns an int when called with one argument,
    otherwise the same type as the number. ndigits may be negative.

    See the test_round method in future/tests/test_builtins.py for
    examples.
    """
    return_int = False
    if ndigits is None:
        return_int = True
        ndigits = 0
    if hasattr(number, '__round__'):
        return number.__round__(ndigits)

    if ndigits < 0:
        raise NotImplementedError('negative ndigits not supported yet')
    exponent = Decimal('10') ** (-ndigits)

    if PYPY:
        # Work around issue #24: round() breaks on PyPy with NumPy's types
        if 'numpy' in repr(type(number)):
            number = float(number)

    if isinstance(number, Decimal):
        d = number
    else:
        if not PY26:
            d = Decimal.from_float(number).quantize(exponent,
                                                rounding=ROUND_HALF_EVEN)
        else:
            d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)

    if return_int:
        return int(d)
    else:
        return float(d)


### From Python 2.7's decimal.py. Only needed to support Py2.6: 
开发者ID:alfa-addon,项目名称:addon,代码行数:47,代码来源:newround.py


注:本文中的decimal.Decimal.from_float方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。