Exemple #1
0
def main():
    while True:
        print('''Please enter the quadratic by giving these values:
            ax^2+bx+c=0''')
        a = float(input('Value of a: '))
        b = float(input('Value of b: '))
        c = float(input('Value of c: '))
        in_square_root_value_1 = operator.mul(-4, operator.mul(a, c))
        in_square_root_value = operator.add(operator.pow(b, 2),
                                            in_square_root_value_1)
        if in_square_root_value < 0:
            print('There is no square root of negative numbers')
            raise Exception(
                f'{ZeroDivisionError} There is no square root of negative numbers.'
            )
        else:
            square_root_value = operator.pow(in_square_root_value, 0.5)
            ans_1_working_out_1 = operator.sub(operator.mul(b, -1),
                                               square_root_value)
            ans_2_working_out_1 = operator.add(operator.mul(b, -1),
                                               square_root_value)
            bottom_value = operator.mul(2, a)
            ans_1 = operator.truediv(ans_1_working_out_1, bottom_value)
            ans_2 = operator.truediv(ans_2_working_out_1, bottom_value)
            if ans_2.is_integer():
                ans_2 = int(ans_2)
            if ans_1.is_integer():
                ans_1 = int(ans_1)
            print(f'''x = {ans_1} or
x = {ans_2}''')
 def test_exponentiation(self, input_tuple, expected):
     self.ureg.default_as_delta = False
     in1, in2 = input_tuple
     if type(in1) is tuple and type(in2) is tuple:
         in1, in2 = self.QP_(*in1), self.QP_(*in2)
     elif not type(in1) is tuple and type(in2) is tuple:
         in1, in2 = self.NON_INT_TYPE(in1), self.QP_(*in2)
     else:
         in1, in2 = self.QP_(*in1), self.NON_INT_TYPE(in2)
     input_tuple = in1, in2
     expected_copy = expected[:]
     for i, mode in enumerate([False, True]):
         self.ureg.autoconvert_offset_to_baseunit = mode
         if expected_copy[i] == "error":
             with pytest.raises(
                 (OffsetUnitCalculusError, DimensionalityError)):
                 op.pow(in1, in2)
         else:
             if type(expected_copy[i]) is tuple:
                 expected = self.QP_(*expected_copy[i])
                 assert op.pow(in1, in2).units == expected.units
             else:
                 expected = expected_copy[i]
             helpers.assert_quantity_almost_equal(op.pow(in1, in2),
                                                  expected)
    def test_integers_to_negative_integer_power(self):
        # Note that the combination of uint64 with a signed integer
        # has common type np.float64. The other combinations should all
        # raise a ValueError for integer ** negative integer.
        exp = [np.array(-1, dt)[()] for dt in 'bhilq']

        # 1 ** -1 possible special case
        base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, 1.)

        # -1 ** -1 possible special case
        base = [np.array(-1, dt)[()] for dt in 'bhilq']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, -1.)

        # 2 ** -1 perhaps generic
        base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, .5)
    def test_integers_to_negative_integer_power(self):
        # Note that the combination of uint64 with a signed integer
        # has common type np.float64. The other combinations should all
        # raise a ValueError for integer ** negative integer.
        exp = [np.array(-1, dt)[()] for dt in 'bhilq']

        # 1 ** -1 possible special case
        base = [np.array(1, dt)[()] for dt in 'bhilqBHILQ']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, 1.)

        # -1 ** -1 possible special case
        base = [np.array(-1, dt)[()] for dt in 'bhilq']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, -1.)

        # 2 ** -1 perhaps generic
        base = [np.array(2, dt)[()] for dt in 'bhilqBHILQ']
        for i1, i2 in itertools.product(base, exp):
            if i1.dtype != np.uint64:
                assert_raises(ValueError, operator.pow, i1, i2)
            else:
                res = operator.pow(i1, i2)
                assert_(res.dtype.type is np.float64)
                assert_almost_equal(res, .5)
Exemple #5
0
    def _build_filter_expression(key, values):
        def in_(lhs, rhs):
            return lhs << ([i.strip() for i in rhs.split(',')])

        operations = {
            'eq': operator.eq,
            'ne': operator.ne,
            'ge': operator.ge,
            'gt': operator.gt,
            'le': operator.le,
            'lt': operator.lt,
            'in': in_,
            'contains': lambda l, r: operator.pow(l, '%%%s%%' % r),
            'startswith': lambda l, r: operator.pow(l, '%s%%' % r),
            'endswith': lambda l, r: operator.pow(l, '%%%s' % r),
            'regex': lambda l, r: l.regexp(r),
        }
        if key.find('__') != -1:
            key, op = key.rsplit('__', 1)
            if op not in operations:
                error('Unrecognized operation: %s. Supported operations are:'
                      '\n%s' % (op, '\n'.join(sorted(operations.keys()))))
        else:
            op = 'eq'

        op = operations[op]
        if isinstance(values, (list, tuple)):
            expr = reduce(operator.or_,
                          [((Metadata.key == key) & op(Metadata.value, value))
                           for value in values])
        else:
            expr = ((Metadata.key == key) & op(Metadata.value, values))

        return fn.EXISTS(Metadata.select().where(
            expr & (Metadata.document == Document._meta.primary_key)))
Exemple #6
0
    def _build_filter_expression(self, key, values):
        def in_(lhs, rhs):
            return lhs << ([i.strip() for i in rhs.split(",")])

        operations = {
            "eq": operator.eq,
            "ne": operator.ne,
            "ge": operator.ge,
            "gt": operator.gt,
            "le": operator.le,
            "lt": operator.lt,
            "in": in_,
            "contains": lambda l, r: operator.pow(l, "%%%s%%" % r),
            "startswith": lambda l, r: operator.pow(l, "%s%%" % r),
            "endswith": lambda l, r: operator.pow(l, "%%%s" % r),
            "regex": lambda l, r: l.regexp(r),
        }
        if key.find("__") != -1:
            key, op = key.rsplit("__", 1)
            if op not in operations:
                error(
                    "Unrecognized operation: %s. Supported operations are:"
                    "\n%s" % (op, "\n".join(sorted(operations.keys())))
                )
        else:
            op = "eq"

        op = operations[op]
        if isinstance(values, (list, tuple)):
            expr = reduce(operator.or_, [((Metadata.key == key) & op(Metadata.value, value)) for value in values])
        else:
            expr = (Metadata.key == key) & op(Metadata.value, values)

        return fn.EXISTS(Metadata.select().where(expr & (Metadata.document == Document._meta.primary_key)))
Exemple #7
0
 def std(self):
     Ex, Ex2, length = 0, 0, float(len(self))
     for i in self:
         Ex += i
         Ex2 += pow(i, 2)
     Ex /= length
     Ex2 /= length
     return sqrt(Ex2 - pow(Ex2, 2))
def slopeCalculation(pt1,pt2):
    dx2=operator.pow(operator.abs(operator.sub(pt1.X,pt2.X)),2)
    dy2=operator.pow(operator.abs(operator.sub(pt1.Y,pt2.Y)),2)
    dz2=operator.pow(operator.abs(operator.sub(pt1.Z,pt2.Z)),2)
    if dz2>0:
        vertical=operator.pow(dz2,0.5)
        horiz=operator.pow(dx2+dy2,0.5)
        slope=(vertical/horiz)*100
    else:
        slope=999
    return slope
Exemple #9
0
def two_of_three(a, b, c):
    """Return x*x + y*y, where x and y are the two largest members of the
    positive numbers a, b, and c.

    >>> two_of_three(1, 2, 3)
    13
    >>> two_of_three(5, 3, 1)
    34
    >>> two_of_three(10, 2, 8)
    164
    >>> two_of_three(5, 5, 5)
    50
    """
    return pow(a,2) + pow(b,2) + pow(c,2) - pow(min(a,b,c), 2)
Exemple #10
0
def find_value_c():
    b = float(input('Value of b: '))
    a = float(input('Value of a: '))
    b_squared = operator.pow(b, 2)
    a_squared = operator.pow(a, 2)
    h_squared = operator.add(b_squared, a_squared)
    if h_squared < 0:
        print('There is no square root of negative numbers')
        raise Exception(
            f'{ZeroDivisionError} there is no square root of negative numbers.'
        )
    h = operator.pow(h_squared, 0.5)
    print(f'Value of h is {h}')
    main()
Exemple #11
0
def find_value_b():
    h = float(input('Value of h: '))
    a = float(input('Value of a: '))
    h_squared = operator.pow(h, 2)
    a_squared = operator.pow(a, 2)
    b_squared = operator.sub(h_squared, a_squared)
    if b_squared < 0:
        print('There is no square root of negative numbers')
        raise Exception(
            f'{ZeroDivisionError} there is no square root of negative numbers.'
        )
    b = operator.pow(b_squared, 0.5)
    print(f'Value of b is {b}')
    main()
Exemple #12
0
def classify(trades, new_trades, labels):
    k = 1
    result = []

    for test in new_trades:
        distances = []
        length = len(test)
        for t in range(len(trades)):
            distance = 0
            for f in range(length):
                distance += pow((trades[t][f] - test[f]), 2)
            distances.append((trades[t], labels[t], sqrt(distance)))

        distances.sort(key=itemgetter(2))
        neighbors = []
        for x in range(k):
            neighbors.append(distances[x][1])

        classVotes = {}
        for x in neighbors:
            if x in classVotes:
                classVotes[x] += 1
            else:
                classVotes[x] = 1
        sortedVotes = sorted(
            classVotes.items(), key=itemgetter(1), reverse=True)

        result.append(sortedVotes[0][0])

    return result
Exemple #13
0
def test_different_probabilities_avg_edges():
    b = 2
    k = 5
    l = 2
    theta = [[0.7, 0.4], [0.4, 0.5]]
    vertices = range(operator.pow(b, k))
    n = 100

    possible_edges = list(itertools.product(vertices, repeat=2))
    counts = {edge: 0 for edge in possible_edges}

    for i in range(n):
        g = model.mKPGM(theta, k, b, l)
        for e in possible_edges:
            if e in g.edges:
                counts[e] += 1

    S = sum(theta[0]) + sum(theta[1])
    S_2 = np.square(theta[0][0]) + np.square(theta[0][1]) \
        + np.square(theta[1][0]) + np.square(theta[1][1])

    exp_num_edges = np.power(S, k)
    var_num_edges = np.power(S, k-1) * (np.power(S, k-l) - 1) \
                * float(S-S_2)/(S-1) + (np.power(S, k-l) - np.power(S_2, l)) \
                * np.power(S, 2*(k-l))

    avg_edges = float(sum(counts.values())) / n

    assert avg_edges >= exp_num_edges - var_num_edges
    assert avg_edges <= exp_num_edges + var_num_edges
Exemple #14
0
def power(a, b):
    """Redefine pow function to prevent too large numbers"""
    if a == 0.0:
        return 0.0
    elif b / math.log(max_value, abs(a)) >= 1:
        raise ValueError((a, b))
    return op.pow(a, b)
Exemple #15
0
def emit_tests(fout=None):
    gen_tests_with_file(fout, 'mul', 2, operator.mul)
    gen_tests_with_file(fout, 'add', 2, operator.add)
    gen_tests_with_file(fout, 'sub', 2, operator.sub)
    gen_tests_with_file(fout, 'sqr', 1, lambda x: operator.pow(x, 2))
    gen_tests_with_file(fout,
                        'mod',
                        2,
                        operator.mod,
                        reject=lambda p, d: d == 0)
    gen_tests_with_file(fout,
                        'div',
                        2,
                        operator.div,
                        reject=lambda p, d: d == 0)
    gen_tests_with_file(fout, 'shl', 2, operator.ilshift, sizesb=SHIFT_SIZES)
    gen_tests_with_file(fout, 'shr', 2, operator.irshift, sizesb=SHIFT_SIZES)
    gen_tests_with_file(fout, 'trunc', 2, trunc, sizesb=SHIFT_SIZES)
    gen_tests_with_file(fout, 'modmul', 3, lambda x, y, p: (x * y) % p)
    gen_tests_with_file(fout, 'modexp', 3, pow, sizesb=EXP_SIZES)
    gen_tests_with_file(fout, 'gcd', 2, gcd)
    gen_tests_with_file(fout, 'egcd-v', 2, egcd_v)
    gen_tests_with_file(fout, 'egcd-a', 2, egcd_a)
    gen_tests_with_file(fout, 'egcd-b', 2, egcd_b)
    gen_tests_with_file(fout, 'modinv', 2, modinv, reject=gcd_eq_zero)
Exemple #16
0
    def calculation(self):
        """
        Function that represents logic of calculation.

        :return:None.
        """
        err = 0
        if self.numberone != '':
            self.is_operation = True
        if self.result != None:
            self.numberone = str(self.result)
        if self.numberone != '' and self.numberdva != '':
            num1 = float(self.numberone)
            num2 = float(self.numberdva)
            if self.operation == '+':
                self.result = add(num1, num2)
            elif self.operation == '-':
                self.result = sub(num1, num2)
            elif self.operation == '*':
                self.result = mul(num1, num2)
            elif self.operation == '/':
                try:
                    self.result = truediv(num1, num2)
                except ZeroDivisionError:
                    self.reset()
                    err = 1
            elif self.operation == '^':
                self.result = pow(num1, num2)
            if err == 0:
                self.ui.lcd.display(self.result)
                self.numberdva = ''
 def test_pow(self):
     self.failUnlessRaises(TypeError, operator.pow)
     self.failUnlessRaises(TypeError, operator.pow, None, None)
     self.assertEqual(operator.pow(3, 5), 3**5)
     self.assertEqual(operator.__pow__(3, 5), 3**5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
Exemple #18
0
 def test_exponentiation_array_exp_2(self):
     arr = np.array(range(3), dtype=np.float)
     # q = self.Q_(copy.copy(arr), None)
     q = self.Q_(copy.copy(arr), "meter")
     arr_cp = copy.copy(arr)
     q_cp = copy.copy(q)
     # this fails as expected since numpy 1.8.0 but...
     with pytest.raises(DimensionalityError):
         op.pow(arr_cp, q_cp)
     # ..not for op.ipow !
     # q_cp is treated as if it is an array. The units are ignored.
     # Quantity.__ipow__ is never called
     arr_cp = copy.copy(arr)
     q_cp = copy.copy(q)
     with pytest.raises(DimensionalityError):
         op.ipow(arr_cp, q_cp)
Exemple #19
0
    def expr(self, p):
        op = p[1]
        left = self._sumDiceRolls(p.expr0)
        right = self._sumDiceRolls(p.expr1)

        if op == '+':
            return operator.add(left, right)
        elif op == '-':
            return operator.sub(left, right)
        elif op == '*':
            if (-self.MAX_MULT <= left <= self.MAX_MULT
                    and -self.MAX_MULT <= right <= self.MAX_MULT):
                return operator.mul(left, right)
            else:
                raise InvalidOperandsException(
                    'multiplication operands are larger than the maximum {}'.
                    format(self.MAX_MULT))
        elif op == '/':
            return operator.floordiv(left, right)
        elif op == '%':
            return operator.mod(left, right)
        elif op == '^':
            if (-self.MAX_EXPONENT <= left <= self.MAX_EXPONENT
                    and -self.MAX_EXPONENT <= right <= self.MAX_EXPONENT):
                return operator.pow(left, right)
            else:
                raise InvalidOperandsException(
                    'operand or exponent is larger than the maximum {}'.format(
                        self.MAX_EXPONENT))
Exemple #20
0
def main():
    a = -1
    b = 5.0
    c = 2
    d = 6

    for k, v in {"a": a, "b": b, "c": c, "d": d}.items():
        print(k + " =", v)

    print("\nPositive/Negative:")
    print("abs(a);", operator.abs(a))
    print("neg(a);", operator.neg(a))
    print("neg(b);", operator.neg(b))
    print("pos(a);", operator.pos(a))
    print("pos(b);", operator.pos(b))

    print("\nArithmetic:")
    print("add(a, b)     :", operator.add(a, b))
    print("floordiv(a, b):", operator.floordiv(a, b))
    print("floordiv(d, c):", operator.floordiv(d, c))
    print("mod(a, b)     :", operator.mod(a, b))
    print("mul(a, b)     :", operator.mul(a, b))
    print("pow(c, d)     :", operator.pow(c, d))
    print("sub(b, a)     :", operator.sub(b, a))
    print("truediv(a, b) :", operator.truediv(a, b))
    print("truediv(d, c) :", operator.truediv(d, c))

    print("\nBitwise:")
    print("and_(c, d)  :", operator.and_(c, d))
    print("invert(c)   :", operator.invert(c))
    print("lshift(c, d):", operator.lshift(c, d))
    print("or_(c, d)   :", operator.or_(c, d))
    print("rshift(d, c):", operator.rshift(d, c))
    print("xor(c, d)   :", operator.xor(c, d))
Exemple #21
0
 def test_pow(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.pow)
     self.assertRaises(TypeError, operator.pow, None, None)
     self.assertEqual(operator.pow(3,5), 3**5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
Exemple #22
0
    def evaluate(self):
        result = None
        left = self.left.evaluate()
        right = self.right.evaluate()

        if self.operation == '+':
            result = operator.add(left, right)
        elif self.operation == '-':
            result = operator.sub(left, right)
        elif self.operation == '*':
            result = operator.mul(left, right)
        elif self.operation == '/':
            result = operator.div(left, right)
        elif self.operation == '^':
            result = operator.pow(left, right)
        elif self.operation == 'and':
            result = left and right
        elif self.operation == 'or':
            result = left or right
        elif self.operation == '<':
            result = operator.lt(left, right)
        elif self.operation == '<=':
            result = operator.le(left, right)
        elif self.operation == '==':
            result = operator.eq(left, right)
        elif self.operation == '!=':
            result = operator.ne(left, right)
        elif self.operation == '>':
            result = operator.gt(left, right)
        elif self.operation == '>=':
            result = operator.ge(left, right)
        elif self.operation == 'in':
            result = (left in right)
        return result
Exemple #23
0
 def test_pow(self):
     self.failUnlessRaises(TypeError, operator.pow)
     self.failUnlessRaises(TypeError, operator.pow, None, None)
     self.failUnless(operator.pow(3,5) == 3**5)
     self.failUnless(operator.__pow__(3,5) == 3**5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
 def test_pow(self):
     self.assertRaises(TypeError, operator.pow)
     self.assertRaises(TypeError, operator.pow, None, None)
     self.assertEqual(operator.pow(3, 5), 3 ** 5)
     self.assertEqual(operator.__pow__(3, 5), 3 ** 5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
Exemple #25
0
def test_random_graph_density():
    b = 2
    prob = 0.65
    theta = [[prob, prob], [prob, prob]]
    k = 5
    vertices = range(operator.pow(b, k))
    n = 100

    possible_edges = list(itertools.product(vertices, repeat=2))
    counts = {edge: 0 for edge in possible_edges}

    p = np.round(np.power(prob, k), decimals=2)

    densities = []

    for i in range(n):
        g = model.KPGM(theta, k, b)
        g.create_igraph()
        graph = g.igraph

        N = graph.vcount()
        E = graph.ecount()
        # D = (2 * E) / float(N * (N - 1))
        D = (E) / float(N * (N - 1))

        densities.append(D)

    mean = np.round(np.mean(densities), decimals=2)

    assert p <= mean + 0.025 and p >= mean - 0.025
Exemple #26
0
 def test_pow(self):
     #operator = self.module
     self.assertRaises(TypeError, operator.pow)
     self.assertRaises(TypeError, operator.pow, None, None)
     self.assertEqual(operator.pow(3, 5), 3**5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
Exemple #27
0
def test_diff_probabilities_edges():
    b = 2
    k = 2
    theta = [[0.7, 0.4], [0.4, 0.5]]
    vertices = range(operator.pow(b, k))
    n = 100

    possible_edges = list(itertools.product(vertices, repeat=2))
    counts = {edge: 0 for edge in possible_edges}

    for i in range(n):
        g = model.KPGM(theta, k, b)
        for e in possible_edges:
            if e in g.edges:
                counts[e] += 1

    P_k = np.kron(np.array(theta), np.array(theta))

    for (i, j) in counts.keys():
        p = P_k[i][j]
        mean = n * p
        variance = n * p * (1 - p)

        cnt = counts[(i, j)]

        assert cnt >= mean - variance
        assert cnt <= mean + variance
Exemple #28
0
 def operator_pow(size):
     a = Array(size, 'int32')
     b = Array(size, 'int32')
     for i in range(size):
         a[i] = nb_types.int32(i+1)
         b[i] = nb_types.int32(size-i)
     return operator.pow(a, b)
Exemple #29
0
 def test_pow(self):
     self.assertRaises(TypeError, operator.pow)
     self.assertRaises(TypeError, operator.pow, None, None)
     self.assertTrue(operator.pow(3, 5) == 3**5)
     self.assertTrue(operator.__pow__(3, 5) == 3**5)
     self.assertRaises(TypeError, operator.pow, 1)
     self.assertRaises(TypeError, operator.pow, 1, 2, 3)
Exemple #30
0
    def p_expression_binop(self, p):
        """expression : expression PLUS expression
                      | expression MINUS expression
                      | expression TIMES expression
                      | expression DIVIDE expression
                      | expression MODULUS expression
                      | expression EXPONENT expression"""

        op = p[2]
        left = self._sumDiceRolls(p[1])
        right = self._sumDiceRolls(p[3])

        if op == '+':
            p[0] = operator.add(left, right)
        elif op == '-':
            p[0] = operator.sub(left, right)
        elif op == '*':
            p[0] = operator.mul(left, right)
        elif op == '/':
            p[0] = operator.floordiv(left, right)
        elif op == '%':
            p[0] = operator.mod(left, right)
        elif op == '^':
            if -self._MAX_EXPONENT <= left <= self._MAX_EXPONENT and -self._MAX_EXPONENT <= right <= self._MAX_EXPONENT:
                p[0] = operator.pow(left, right)
            else:
                raise InvalidOperandsException(u'operand or exponent is larger than the maximum {}'
                                               .format(self._MAX_EXPONENT))
Exemple #31
0
def apply_pow(left: Column, right):
    if type(right) == Column:
        result, index = apply_fast_pow(left.values, right.values,
                                       left.index, right.index)
        return Column(result, index)

    else:
        return Column(operator.pow(left.values, right), left.index)
Exemple #32
0
def limited_power(a, b):
    """
    A limited power function to make sure that
    commands do not take too long to process.
    """
    if any(abs(n) > 1000 for n in [a, b]):
        raise OverflowError("{}**{} is too big".format(a, b))
    return op.pow(a, b)
Exemple #33
0
def exponentiation(*args, power=2):
    """
    Raises a set of numbers to a power
    :param args: Number for power
    :param power: Power
    :return list: Number to power
    """
    return list(map(lambda x: pow(x, power), args))
Exemple #34
0
def limited_power(a, b):
    """
    A limited power function to make sure that
    commands do not take too long to process.
    """
    if any(abs(n) > 100 for n in [a, b]):
        raise ValueError(a, b)
    return op.pow(a, b)
Exemple #35
0
def my_pow_external2(v1, v2):
    if v1 is None:
        v1 = D * [1.0]
    if v2 is None:
        v2 = D * [1.0]
    v1 = norm_logistic(v1)
    v2 = norm_logistic(v2)
    return adjust_vector([operator.pow(x, y) for x, y in zip(v1, v2)])
def calculate_bmi(person_details):
    '''
    this method takes list of objects as input and yields the object with its calculated BMI to the caller.
    '''
    for person in person_details:
        bmi = round((person["WeightKg"] * 10000) /
                    (operator.pow(person["HeightCm"], 2)), 2)
        yield person, bmi
Exemple #37
0
def _power(left, right):
    from .compat import is_duck_array
    from .quantity import Quantity

    if (isinstance(left, Quantity) and is_duck_array(left.magnitude)
            and left.dtype.kind not in "cf" and right < 0):
        left = left.astype(float)

    return operator.pow(left, right)
Exemple #38
0
    def std(self):
        Ex, Ex2, length = 0, 0, float(len(self))
        if length <= 1:
            return 0

        for val in self:
            Ex += val
            Ex2 += pow(val, 2)
        return sqrt((Ex2 - Ex**2 / length) / (length - 1.0))
Exemple #39
0
def pow_type3(p1, p2, p3):
    v1 = p1.vec
    v2 = p2.vec
    v3 = p3.vec

    if v1 is None:
        v1 = D * [1.0]
    if v2 is None:
        v2 = D * [1.0]
    if v3 is None:
        v3 = D * [1.0]
    v1 = norm_logistic(v1)
    v2 = norm_logistic(v2)
    v3 = norm_logistic(v3)
    return Type3(
        adjust_vector([
            operator.pow(operator.pow(x, y), z) for x, y, z in zip(v1, v2, v3)
        ]))
Exemple #40
0
def math(op, d1, d2):
    ops = {
        '**': operator.pow(d1, d2),
        '*': operator.mul(d1, d2),
        '/': operator.truediv(d1, d2),
        '//': operator.floordiv(d1, d2),
        '+': operator.add(d1, d2),
        '-': operator.sub(d1, d2)
    }
    return ops.get(op)
Exemple #41
0
def guarded_power(a, b):
    """A limited power function to make sure that
    commands do not take too long to process.
    """
    if any(abs(n) > 1000 for n in [a, b]):
        raise CalcError("would take too long to calculate")
    try:
        return op.pow(a, b)
    except OverflowError:
        raise CalcError("too large to represent as float")
Exemple #42
0
        def check(other):
            _check_op(other, operator.add)
            _check_op(other, operator.sub)
            _check_op(other, operator.div)
            _check_op(other, operator.mul)
            _check_op(other, operator.pow)

            _check_op(other, lambda x, y: operator.add(y, x))
            _check_op(other, lambda x, y: operator.sub(y, x))
            _check_op(other, lambda x, y: operator.div(y, x))
            _check_op(other, lambda x, y: operator.mul(y, x))
            _check_op(other, lambda x, y: operator.pow(y, x))
Exemple #43
0
def limited_power(a, b):
    """A limited power function to make sure that
    commands do not take too long to process.
    """
    for n in (a, b):
        if is_too_long(n):
            # Neaten the error message
            raise OverflowError("result is too long to be printed")

    if any(abs(n) > 1000 for n in [a, b]):
        raise OverflowError("{}**{} would take too long to calculate".format(a, b))
    return op.pow(a, b)
Exemple #44
0
 def test_exponentiation(self, input_tuple, expected):
     self.ureg.default_as_delta = False
     in1, in2 = input_tuple
     if type(in1) is tuple and type(in2) is tuple:
         in1, in2 = self.Q_(*in1), self.Q_(*in2)
     elif not type(in1) is tuple and type(in2) is tuple:
         in2 = self.Q_(*in2)
     else:
         in1 = self.Q_(*in1)
     input_tuple = in1, in2
     expected_copy = expected[:]
     for i, mode in enumerate([False, True]):
         self.ureg.autoconvert_offset_to_baseunit = mode
         if expected_copy[i] == 'error':
             self.assertRaises((OffsetUnitCalculusError,
                                DimensionalityError), op.pow, in1, in2)
         else:
             if type(expected_copy[i]) is tuple:
                 expected = self.Q_(*expected_copy[i])
                 self.assertEqual(op.pow(in1, in2).units, expected.units)
             else:
                 expected = expected_copy[i]
             self.assertQuantityAlmostEqual(op.pow(in1, in2), expected)
def guarded_pow(left, right):
    # Only handle ints because floats will overflow anyway.
    if not isinstance(left, numbers.Integral):
        pass
    elif not isinstance(right, numbers.Integral):
        pass
    elif pow_complexity(left, right) < 0.5:
        # Value 0.5 is arbitary and based on a estimated runtime of 0.5s
        # on a fairly decent laptop processor.
        pass
    else:
        raise ValueError("Pow expression too complex to calculate.")

    return operator.pow(left, right)
Exemple #46
0
    def _build_filter_expression(key, values):
        def in_(lhs, rhs):
            return lhs << ([i.strip() for i in rhs.split(',')])
        operations = {
            'eq': operator.eq,
            'ne': operator.ne,
            'ge': operator.ge,
            'gt': operator.gt,
            'le': operator.le,
            'lt': operator.lt,
            'in': in_,
            'contains': lambda l, r: operator.pow(l, '%%%s%%' % r),
            'startswith': lambda l, r: operator.pow(l, '%s%%' % r),
            'endswith': lambda l, r: operator.pow(l, '%%%s' % r),
            'regex': lambda l, r: l.regexp(r),
        }
        if key.find('__') != -1:
            key, op = key.rsplit('__', 1)
            if op not in operations:
                error(
                    'Unrecognized operation: %s. Supported operations are:'
                    '\n%s' % (op, '\n'.join(sorted(operations.keys()))))
        else:
            op = 'eq'

        op = operations[op]
        if isinstance(values, (list, tuple)):
            expr = reduce(operator.or_, [
                ((Metadata.key == key) & op(Metadata.value, value))
                for value in values])
        else:
            expr = ((Metadata.key == key) & op(Metadata.value, values))

        return fn.EXISTS(Metadata.select().where(
            expr &
            (Metadata.document == Document._meta.primary_key)))
Exemple #47
0
    def cal_overlap(self):
        list_intersect = self.intersect()
        list_union = self.union()
        freq_inter = 0.0
        freq_union = 0.0
        for item in list_intersect:
            matches_intersect = [x for x in self.list_corpus if item == x]
            freq_inter += math.log10(operator.pow(len(matches_intersect) + 1, -1))

        for item in list_union:
            if len(list_union)==0:
                print self.str_1,self.str_2
            matches_union = [x for x in self.list_corpus if item == x]
            freq_union += math.log10(operator.pow(len(matches_union) + 1, -1))
        #print "cor", self.list_corpus
        #print list_intersect,list_union
        idf_overlap = freq_inter / freq_union
        return idf_overlap
        # print matches_intersect, freq_inter
        # print matches_union, freq_union
        #
        # print "intersect", list_intersect
        # print "union", list_union
        # print "corpus", self.list_corpus
Exemple #48
0
        def check(series, other):
            simple_ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'mod']

            for opname in simple_ops:
                _check_op(series, other, getattr(operator, opname))

            _check_op(series, other, operator.pow, pos_only=True)

            _check_op(series, other, lambda x, y: operator.add(y, x))
            _check_op(series, other, lambda x, y: operator.sub(y, x))
            _check_op(series, other, lambda x, y: operator.truediv(y, x))
            _check_op(series, other, lambda x, y: operator.floordiv(y, x))
            _check_op(series, other, lambda x, y: operator.mul(y, x))
            _check_op(series, other, lambda x, y: operator.pow(y, x),
                      pos_only=True)
            _check_op(series, other, lambda x, y: operator.mod(y, x))
Exemple #49
0
 def __rpow__(self, other, modulo=None):
     if modulo is None:
         coerced = _coerce(self, other)
         if coerced is None or coerced[0] is self:
             func = instance_getattr1(self, '__rpow__', False)
             if func:
                 return func(other)
             return NotImplemented
         else:
             return operator.pow(coerced[1], coerced[0], None)
     else:
         # CPython also doesn't try coercion in this case
         func = instance_getattr1(self, '__rpow__', False)
         if func:
             return func(other, modulo)
         return NotImplemented
Exemple #50
0
def emit_tests(fout = None):
    gen_tests_with_file(fout, 'mul', 2, operator.mul)
    gen_tests_with_file(fout, 'add', 2, operator.add)
    gen_tests_with_file(fout, 'sub', 2, operator.sub)
    gen_tests_with_file(fout, 'sqr', 1, lambda x: operator.pow(x, 2))
    gen_tests_with_file(fout, 'mod', 2, operator.mod, reject = lambda p, d: d == 0)
    gen_tests_with_file(fout, 'div', 2, operator.div, reject = lambda p, d: d == 0)
    gen_tests_with_file(fout, 'shl', 2, operator.ilshift, sizesb = SHIFT_SIZES)
    gen_tests_with_file(fout, 'shr', 2, operator.irshift, sizesb = SHIFT_SIZES)
    gen_tests_with_file(fout, 'trunc', 2, trunc, sizesb = SHIFT_SIZES)
    gen_tests_with_file(fout, 'modmul', 3, lambda x, y, p: (x * y) % p)
    gen_tests_with_file(fout, 'modexp', 3, pow, sizesb = EXP_SIZES)
    gen_tests_with_file(fout, 'gcd', 2, gcd)
    gen_tests_with_file(fout, 'egcd-v', 2, egcd_v)
    gen_tests_with_file(fout, 'egcd-a', 2, egcd_a)
    gen_tests_with_file(fout, 'egcd-b', 2, egcd_b)
    gen_tests_with_file(fout, 'modinv', 2, modinv, reject = gcd_eq_zero)
Exemple #51
0
 def pow_usecase(x, y):
     return operator.pow(x, y)
Exemple #52
0
 def test_bad_power(self):
     msg = "Cannot raise .* a 'no-unit'"
     with self.assertRaisesRegexp(ValueError, msg):
         operator.pow(self.u, 0.4)
Exemple #53
0
 def test_unit_power(self):
     v = Unit('m')
     msg = 'argument must be a string or a number'
     with self.assertRaisesRegexp(TypeError, msg):
         operator.pow(self.u, v)
def sqrt(num):
    return(operator.pow(num, 0.5))
Exemple #55
0
 def test_not_numeric(self):
     with self.assertRaisesRegexp(TypeError, 'numeric value is required'):
         operator.pow(self.u, 'not_a_number')
Exemple #56
0
import operator
print(operator.truediv(245850922, 78256779))
print(operator.truediv(operator.add(1, operator.pow(5, 0.5)), 2))
Exemple #57
0
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 11:33:36 2015

@author: A
"""
import operator
# r = 245850922 / 78256779
rr = operator.truediv(245850922, 78256779)
tt = (1+operator.pow(5, 0.5))/2
# t= (1+5**0.5)/2
print(rr)
print(tt)
Exemple #58
0
 def __rpow__(self, y):
   return NonStandardInteger(operator.pow(y, self.val))
Exemple #59
0
import es
from random import randint
from math import sin, cos, tan, asin, acos, atan
from operator import add, sub, mul, pow, truediv as div
from ..val import sv, STR, INT, NUM, VAR, ANY
from . import Command

root = lambda a, b: pow(a, 1.0/b)

_math_operators = {
  '+': add, 'add': add,
  '-': sub, 'subract': sub,
  '*': mul, 'multiply': mul,
  '/': div, 'divide': div,
  '^': pow, 'power': pow,
  '//': root, 'root': root,
}

_math_functions = ['sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'abs', 'int', 'float']

@Command(syntax='<variable> <operator> [value]', types=(VAR, STR, ANY), desc='EventScripts math functions, courtesy of Cr3V3TT3')
def math(argv):
  var, op = argv[:2]
  val = sv[var]
  if val.isstring():
    raise ValueError('math function called on a non-numeric value: %s, %s' % (var, val.strval))
  val = NUM(val)
  if op in _math_operators:
    if len(argv) < 3:
      raise SyntaxError
    val2 = argv[2]
Exemple #60
0
 def test_bad_power(self):
     u = Unit('m^2')
     msg = 'Cannot raise .* by a decimal'
     with self.assertRaisesRegexp(ValueError, msg):
         operator.pow(u, 0.4)