本文整理汇总了Python中__future__.division方法的典型用法代码示例。如果您正苦于以下问题:Python __future__.division方法的具体用法?Python __future__.division怎么用?Python __future__.division使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类__future__
的用法示例。
在下文中一共展示了__future__.division方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: divide
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def divide(x, y, safe_mode=True, epsilon=None, name=None):
""" A wrapper of `tf.divide`, computes Python style division of x by y but extends safe divide support.
If safe_mode is `True` or epsilon is given(a small float number), the absolute value of denominator
in the division will be clip to make sure it's bigger than epsilon(default is 1e-13).
Args:
safe_mode: Use safe divide mode.
epsilon: Float number. Default is `1e-13`.
"""
if not safe_mode and epsilon is None:
return tf.divide(x, y, name=name)
else:
epsilon = 1e-20 if epsilon is None else epsilon
name = "safe_divide" if name is None else name
with tf.name_scope(name):
y = tf.where(tf.greater(tf.abs(y), epsilon), y, y + tf.sign(y) * epsilon)
return tf.divide(x, y)
示例2: test_truediv
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def test_truediv(Poly):
# true division is valid only if the denominator is a Number and
# not a python bool.
p1 = Poly([1,2,3])
p2 = p1 * 5
for stype in np.ScalarType:
if not issubclass(stype, Number) or issubclass(stype, bool):
continue
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in (int, long, float):
s = stype(5)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for stype in [complex]:
s = stype(5, 0)
assert_poly_almost_equal(op.truediv(p2, s), p1)
assert_raises(TypeError, op.truediv, s, p2)
for s in [tuple(), list(), dict(), bool(), np.array([1])]:
assert_raises(TypeError, op.truediv, p2, s)
assert_raises(TypeError, op.truediv, s, p2)
for ptype in classes:
assert_raises(TypeError, op.truediv, p2, ptype(1))
示例3: __init__
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def __init__(self, shape, dtype):
"""Specify the shape and dtype of the mean to be estimated.
Note that a float mean to zero submitted elements is NaN, while computing
the integer mean of zero elements raises a division by zero error.
Args:
shape: Shape of the mean to compute.
dtype: Data type of the mean to compute.
"""
self._dtype = dtype
self._sum = tf.Variable(lambda: tf.zeros(shape, dtype), False)
self._count = tf.Variable(lambda: 0, trainable=False)
示例4: getTriangleIndex
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def getTriangleIndex(i, j):
# If i == j that's an error.
if i == j:
sys.stderr.write("Can't access triangle matrix with i == j")
sys.exit(1)
# If j < i just swap the values.
if j < i:
temp = i
i = j
j = temp
# Calculate the index within the triangular array.
# This fancy indexing scheme is taken from pg. 211 of:
# http://infolab.stanford.edu/~ullman/mmds/ch6.pdf
# But I adapted it for a 0-based index.
# Note: The division by two should not truncate, it
# needs to be a float.
k = int(i * (numDocs - (i + 1) / 2.0) + j - i) - 1
return k
# =============================================================================
# Calculate Jaccard Similarities
# =============================================================================
# In this section, we will directly calculate the Jaccard similarities by
# comparing the sets. This is included here to show how much slower it is than
# the MinHash approach.
# Calculating the Jaccard similarities gets really slow for large numbers
# of documents.
示例5: __init__
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def __init__(self, score_file):
file_string = open(score_file, 'r').read()
file_string = file_string.replace('import jmp_score as jmp', '')
file_string = file_string.replace('from __future__ import division', '')
file_string = file_string.replace('from math import *', '')
file_string = file_string.replace('import numpy as np', '')
self.file_string = file_string
six.exec_(self.file_string, globals())
try:
self.input_dict = getInputMetadata()
self.output_dict = getOutputMetadata()
self.model_dict = getModelMetadata()
except NameError:
raise ValueError("The file is not a valid Python scroing file from JMP")
示例6: strip_future_imports
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def strip_future_imports(self, code):
"""
Strips any of these import lines:
from __future__ import <anything>
from future <anything>
from future.<anything>
from builtins <anything>
or any line containing:
install_hooks()
or:
install_aliases()
Limitation: doesn't handle imports split across multiple lines like
this:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
"""
output = []
# We need .splitlines(keepends=True), which doesn't exist on Py2,
# so we use this instead:
for line in code.split('\n'):
if not (line.startswith('from __future__ import ')
or line.startswith('from future ')
or line.startswith('from builtins ')
or 'install_hooks()' in line
or 'install_aliases()' in line
# but don't match "from future_builtins" :)
or line.startswith('from future.')):
output.append(line)
return '\n'.join(output)
示例7: calculate
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def calculate( self, operand1, operator, operand2 ):
""" perform calculation """
if operator == "+": # addition operation
result = operand1 + operand2
elif operator == "-": # subtraction operation
result = operand1 - operand2
elif operator == "*": # multiplication operation
result = operand1 * operand2
elif operator == "/": # division operation
result = operand1 / operand2
elif operator == "//": # floor division
result = operand1 // operand2
else: # unrecognizable operator
result = None
return result
##########################################################################
# (C) Copyright 2002 by Deitel & Associates, Inc. and Prentice Hall. #
# All Rights Reserved. #
# #
# DISCLAIMER: The authors and publisher of this book have used their #
# best efforts in preparing the book. These efforts include the #
# development, research, and testing of the theories and programs #
# to determine their effectiveness. The authors and publisher make #
# no warranty of any kind, expressed or implied, with regard to these #
# programs or to the documentation contained in these books. The authors #
# and publisher shall not be liable in any event for incidental or #
# consequential damages in connection with, or arising out of, the #
# furnishing, performance, or use of these programs. #
##########################################################################
示例8: transform
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def transform(self, node, results):
future_import(u"unicode_literals", node)
future_import(u"print_function", node)
future_import(u"division", node)
future_import(u"absolute_import", node)
示例9: match_division
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def match_division(node):
u"""
__future__.division redefines the meaning of a single slash for division,
so we match that and only that.
"""
slash = token.SLASH
return node.type == slash and not node.next_sibling.type == slash and \
not node.prev_sibling.type == slash
示例10: start_tree
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def start_tree(self, tree, name):
"""
Skip this fixer if "__future__.division" is already imported.
"""
super(FixDivisionSafe, self).start_tree(tree, name)
self.skip = "division" in tree.future_features
示例11: transform
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def transform(self, node, results):
if self.skip:
return
future_import(u"division", node)
touch_import_top(u'past.utils', u'old_div', node)
return wrap_in_fn_call("old_div", results, prefix=node.prefix)
示例12: transform
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def transform(self, node, results):
# Reverse order:
future_import(u"print_function", node)
future_import(u"division", node)
future_import(u"absolute_import", node)
示例13: match
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def match(self, node):
u"""
Since the tree needs to be fixed once and only once if and only if it
matches, we can start discarding matches after the first.
"""
if node.type == self.syms.term:
div_idx = find_division(node)
if div_idx is not False:
# if expr1 or expr2 are obviously floats, we don't need to wrap in
# old_div, as the behavior of division between any number and a float
# should be the same in 2 or 3
if not is_floaty(node, div_idx):
return clone_div_operands(node, div_idx)
return False
示例14: arithmetic
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def arithmetic(value, entropy, length=None, add_sub=True, mul_div=True):
"""Generates an arithmetic expression with a given value.
Args:
value: Target value (integer or rational).
entropy: Amount of randomness to use in generating expression.
length: Number of ops to use. If `None` then suitable length will be picked
based on entropy by sampling within the range
`length_range_for_entropy`.
add_sub: Whether to include addition and subtraction operations.
mul_div: Whether to include multiplication and division operations.
Returns:
Instance of `ops.Op` containing expression.
"""
assert isinstance(entropy, float)
if length is None:
min_length, max_length = length_range_for_entropy(entropy)
length = random.randint(min_length, max_length)
# Some entropy used up in sampling the length.
entropy -= math.log10(max_length - min_length + 1)
else:
assert isinstance(length, int)
# Entropy adjustment, because different binary trees (from sampling ops) can
# lead to the same expression. This is the correct value when we use just
# addition as the op, and is otherwise an an upper bound.
entropy += combinatorics.log_number_binary_trees(length) / math.log(10)
value = sympy.sympify(value)
sample_args = _SampleArgs(length, entropy)
return _arithmetic(value, sample_args, add_sub, mul_div)
示例15: _is_simple
# 需要导入模块: import __future__ [as 别名]
# 或者: from __future__ import division [as 别名]
def _is_simple(self):
"""Returns whether it's a simple number, rather than a division or neg."""
if isinstance(self._value, sympy.Symbol):
return True
elif (isinstance(self._value, int)
or isinstance(self._value, sympy.Integer)
or isinstance(self._value, display.Decimal)
or isinstance(self._value, np.int64)):
return self._value >= 0
elif isinstance(self._value, sympy.Rational):
return False
elif isinstance(self._value, sympy.Function):
return True
else:
raise ValueError('Unknown type {}'.format(type(self._value)))