Python math.e() Examples

The following are 30 code examples of math.e(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module math , or try the search function .
Example #1
Source Project: raveberry   Author: raveberry   File: programs.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def stop(self) -> None:
        try:
            os.close(self.cava_fifo)
        except OSError as e:
            logging.info("fifo already closed: %s", e)
        except TypeError as e:
            logging.info("fifo does not exist: %s", e)

        if self.cava_process:
            self.cava_process.terminate()

        try:
            os.remove(self.cava_fifo_path)
        except FileNotFoundError as e:
            # the file was already deleted
            logging.info("%s not found while deleting: %s", self.cava_fifo_path, e) 
Example #2
Source Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    License: Apache License 2.0 6 votes vote down vote up
def test_callback_register_double(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
                             c_double, c_double)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_double
        func.argtypes = (c_double, c_double, c_double,
                         c_double, c_double, CALLBACK)
        func.restype = c_double

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
        self.assertEqual(result,
                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5)) 
Example #3
Source Project: phpsploit   Author: nil0x42   File: SimpleCalc.py    License: GNU General Public License v3.0 6 votes vote down vote up
def evaluateStack( s ):
    op = s.pop()
    if op == 'unary -':
        return -evaluateStack( s )
    if op in "+-*/^":
        op2 = evaluateStack( s )
        op1 = evaluateStack( s )
        return opn[op]( op1, op2 )
    elif op == "PI":
        return math.pi # 3.1415926535
    elif op == "E":
        return math.e  # 2.718281828
    elif op in fn:
        return fn[op]( evaluateStack( s ) )
    elif op[0].isalpha():
        if op in variables:
            return variables[op]
        raise Exception("invalid identifier '%s'" % op)
    else:
        return float( op ) 
Example #4
Source Project: phpsploit   Author: nil0x42   File: fourFn.py    License: GNU General Public License v3.0 6 votes vote down vote up
def evaluateStack( s ):
    op = s.pop()
    if op == 'unary -':
        return -evaluateStack( s )
    if op in "+-*/^":
        op2 = evaluateStack( s )
        op1 = evaluateStack( s )
        return opn[op]( op1, op2 )
    elif op == "PI":
        return math.pi # 3.1415926535
    elif op == "E":
        return math.e  # 2.718281828
    elif op in fn:
        return fn[op]( evaluateStack( s ) )
    elif op[0].isalpha():
        raise Exception("invalid identifier '%s'" % op)
    else:
        return float( op ) 
Example #5
Source Project: yui   Author: item4   File: calc_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_attribute():
    e = Evaluator()
    e.symbol_table['dt'] = datetime.now()
    e.run('x = dt.year')
    assert e.symbol_table['x'] == e.symbol_table['dt'].year

    err = 'You can not access `test_test_test` attribute'
    with pytest.raises(BadSyntax, match=err):
        e.run('y = dt.test_test_test')

    assert 'y' not in e.symbol_table

    err = 'You can not access `asdf` attribute'
    with pytest.raises(BadSyntax, match=err):
        e.run('z = x.asdf')

    e.symbol_table['math'] = math
    err = 'You can not access `__module__` attribute'
    with pytest.raises(BadSyntax, match=err):
        e.run('math.__module__')

    e.symbol_table['datetime'] = datetime
    err = 'You can not access `test_test` attribute'
    with pytest.raises(BadSyntax, match=err):
        e.run('datetime.test_test') 
Example #6
Source Project: yui   Author: item4   File: calc_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_augassign():
    e = Evaluator()
    e.symbol_table['a'] = 0
    e.run('a += 1')
    assert e.symbol_table['a'] == 1
    e.symbol_table['l'] = [1, 2, 3, 4]
    e.run('l[0] -= 1')
    assert e.symbol_table['l'] == [0, 2, 3, 4]

    err = 'This assign method is not allowed'
    with pytest.raises(BadSyntax, match=err):
        e.run('l[2:3] += 20')

    e.symbol_table['dt'] = datetime.now()
    err = 'This assign method is not allowed'
    with pytest.raises(BadSyntax, match=err):
        e.run('dt.year += 2000') 
Example #7
Source Project: yui   Author: item4   File: calc_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_binop():
    e = Evaluator()
    assert e.run('1 + 2') == 1 + 2
    assert e.run('3 & 2') == 3 & 2
    assert e.run('1 | 2') == 1 | 2
    assert e.run('3 ^ 2') == 3 ^ 2
    assert e.run('3 / 2') == 3 / 2
    assert e.run('3 // 2') == 3 // 2
    assert e.run('3 << 2') == 3 << 2
    with pytest.raises(TypeError):
        e.run('2 @ 3')
    assert e.run('3 * 2') == 3 * 2
    assert e.run('33 % 4') == 33 % 4
    assert e.run('3 ** 2') == 3 ** 2
    assert e.run('100 >> 2') == 100 >> 2
    assert e.run('3 - 1') == 3 - 1 
Example #8
Source Project: yui   Author: item4   File: calc_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_delete():
    e = Evaluator()
    e.symbol_table['a'] = 0
    e.symbol_table['b'] = 0
    e.symbol_table['c'] = 0
    e.run('del a, b, c')
    assert 'a' not in e.symbol_table
    assert 'b' not in e.symbol_table
    assert 'c' not in e.symbol_table
    e.symbol_table['l'] = [1, 2, 3, 4]
    e.run('del l[0]')
    assert e.symbol_table['l'] == [2, 3, 4]

    err = 'This delete method is not allowed'
    with pytest.raises(BadSyntax, match=err):
        e.run('del l[2:3]')

    e.symbol_table['dt'] = datetime.now()
    err = 'This delete method is not allowed'
    with pytest.raises(BadSyntax, match=err):
        e.run('del dt.year') 
Example #9
Source Project: yui   Author: item4   File: calc_test.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_dictcomp():
    e = Evaluator()
    assert e.run('{k+1: v**2 for k, v in {1: 1, 2: 11, 3: 111}.items()}') == {
        2: 1,
        3: 121,
        4: 12321,
    }
    assert 'k' not in e.symbol_table
    assert 'v' not in e.symbol_table
    e.run('a = {k+1: v**2 for k, v in {1: 1, 2: 11, 3: 111}.items()}')
    assert e.symbol_table['a'] == {
        2: 1,
        3: 121,
        4: 12321,
    }
    assert 'k' not in e.symbol_table
    assert 'v' not in e.symbol_table 
Example #10
Source Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 6 votes vote down vote up
def test_isclose():
    from quaternion import x, y

    assert np.array_equal(quaternion.isclose([1e10*x, 1e-7*y], [1.00001e10*x, 1e-8*y], rtol=1.e-5, atol=2.e-8),
                          np.array([True, False]))
    assert np.array_equal(quaternion.isclose([1e10*x, 1e-8*y], [1.00001e10*x, 1e-9*y], rtol=1.e-5, atol=2.e-8),
                          np.array([True, True]))
    assert np.array_equal(quaternion.isclose([1e10*x, 1e-8*y], [1.0001e10*x, 1e-9*y], rtol=1.e-5, atol=2.e-8),
                          np.array([False, True]))
    assert np.array_equal(quaternion.isclose([x, np.nan*y], [x, np.nan*y]),
                          np.array([True, False]))
    assert np.array_equal(quaternion.isclose([x, np.nan*y], [x, np.nan*y], equal_nan=True),
                          np.array([True, True]))

    np.random.seed(1234)
    a = quaternion.as_quat_array(np.random.random((3, 5, 4)))
    assert quaternion.allclose(1e10 * a, 1.00001e10 * a, rtol=1.e-5, atol=2.e-8, verbose=True) == True
    assert quaternion.allclose(1e-7 * a, 1e-8 * a, rtol=1.e-5, atol=2.e-8) == False
    assert quaternion.allclose(1e10 * a, 1.00001e10 * a, rtol=1.e-5, atol=2.e-8, verbose=True) == True
    assert quaternion.allclose(1e-8 * a, 1e-9 * a, rtol=1.e-5, atol=2.e-8, verbose=True) == True
    assert quaternion.allclose(1e10 * a, 1.0001e10 * a, rtol=1.e-5, atol=2.e-8) == False
    assert quaternion.allclose(1e-8 * a, 1e-9 * a, rtol=1.e-5, atol=2.e-8, verbose=True) == True
    assert quaternion.allclose(np.nan * a, np.nan * a) == False
    assert quaternion.allclose(np.nan * a, np.nan * a, equal_nan=True, verbose=True) == True 
Example #11
Source Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 6 votes vote down vote up
def test_allclose(Qs):
    for q in Qs[Qs_nonnan]:
        assert quaternion.allclose(q, q, rtol=0.0, atol=0.0)
    assert quaternion.allclose(Qs[Qs_nonnan], Qs[Qs_nonnan], rtol=0.0, atol=0.0)

    for q in Qs[Qs_finitenonzero]:
        assert quaternion.allclose(q, q*(1+1e-13), rtol=1.1e-13, atol=0.0)
        assert ~quaternion.allclose(q, q*(1+1e-13), rtol=0.9e-13, atol=0.0)
        for e in [quaternion.one, quaternion.x, quaternion.y, quaternion.z]:
            assert quaternion.allclose(q, q+(1e-13*e), rtol=0.0, atol=1.1e-13)
            assert ~quaternion.allclose(q, q+(1e-13*e), rtol=0.0, atol=0.9e-13)
    assert quaternion.allclose(Qs[Qs_finitenonzero], Qs[Qs_finitenonzero]*(1+1e-13), rtol=1.1e-13, atol=0.0)
    assert ~quaternion.allclose(Qs[Qs_finitenonzero], Qs[Qs_finitenonzero]*(1+1e-13), rtol=0.9e-13, atol=0.0)
    for e in [quaternion.one, quaternion.x, quaternion.y, quaternion.z]:
        assert quaternion.allclose(Qs[Qs_finite], Qs[Qs_finite]+(1e-13*e), rtol=0.0, atol=1.1e-13)
        assert ~quaternion.allclose(Qs[Qs_finite], Qs[Qs_finite]+(1e-13*e), rtol=0.0, atol=0.9e-13)
    assert quaternion.allclose(Qs[Qs_zero], Qs[Qs_zero]*2, rtol=0.0, atol=1.1e-13)

    for qnan in Qs[Qs_nan]:
        assert ~quaternion.allclose(qnan, qnan, rtol=1.0, atol=1.0)
        for q in Qs:
            assert ~quaternion.allclose(q, qnan, rtol=1.0, atol=1.0) 
Example #12
Source Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 6 votes vote down vote up
def test_from_spherical_coords():
    np.random.seed(1843)
    random_angles = [[np.random.uniform(-np.pi, np.pi), np.random.uniform(-np.pi, np.pi)]
                     for i in range(5000)]
    for vartheta, varphi in random_angles:
        q = quaternion.from_spherical_coords(vartheta, varphi)
        assert abs((np.quaternion(0, 0, 0, varphi / 2.).exp() * np.quaternion(0, 0, vartheta / 2., 0).exp())
                   - q) < 1.e-15
        xprime = q * quaternion.x * q.inverse()
        yprime = q * quaternion.y * q.inverse()
        zprime = q * quaternion.z * q.inverse()
        nhat = np.quaternion(0.0, math.sin(vartheta)*math.cos(varphi), math.sin(vartheta)*math.sin(varphi),
                             math.cos(vartheta))
        thetahat = np.quaternion(0.0, math.cos(vartheta)*math.cos(varphi), math.cos(vartheta)*math.sin(varphi),
                                 -math.sin(vartheta))
        phihat = np.quaternion(0.0, -math.sin(varphi), math.cos(varphi), 0.0)
        assert abs(xprime - thetahat) < 1.e-15
        assert abs(yprime - phihat) < 1.e-15
        assert abs(zprime - nhat) < 1.e-15
    assert np.max(np.abs(quaternion.from_spherical_coords(random_angles)
                         - np.array([quaternion.from_spherical_coords(vartheta, varphi)
                                     for vartheta, varphi in random_angles]))) < 1.e-15 
Example #13
Source Project: quaternion   Author: moble   File: test_quaternion.py    License: MIT License 6 votes vote down vote up
def test_as_euler_angles():
    np.random.seed(1843)
    random_angles = [[np.random.uniform(-np.pi, np.pi),
                      np.random.uniform(-np.pi, np.pi),
                      np.random.uniform(-np.pi, np.pi)]
                     for i in range(5000)]
    for alpha, beta, gamma in random_angles:
        R1 = quaternion.from_euler_angles(alpha, beta, gamma)
        R2 = quaternion.from_euler_angles(*list(quaternion.as_euler_angles(R1)))
        d = quaternion.rotation_intrinsic_distance(R1, R2)
        assert d < 6e3*eps, ((alpha, beta, gamma), R1, R2, d)  # Can't use allclose here; we don't care about rotor sign
    q0 = quaternion.quaternion(0, 0.6, 0.8, 0)
    assert q0.norm() == 1.0
    assert abs(q0 - quaternion.from_euler_angles(*list(quaternion.as_euler_angles(q0)))) < 1.e-15


# Unary bool returners 
Example #14
Source Project: soccer-matlab   Author: utra-robosoccer   File: utility.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def diag_normal_entropy(mean, logstd):
  """Empirical entropy of a normal with diagonal covariance."""
  constant = mean.shape[-1].value * math.log(2 * math.pi * math.e)
  return (constant + tf.reduce_sum(2 * logstd, 1)) / 2 
Example #15
Source Project: soccer-matlab   Author: utra-robosoccer   File: utility.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def diag_normal_entropy(mean, logstd):
  """Empirical entropy of a normal with diagonal covariance."""
  constant = mean.shape[-1].value * math.log(2 * math.pi * math.e)
  return (constant + tf.reduce_sum(2 * logstd, 1)) / 2 
Example #16
Source Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes vote down vote up
def genpy(self, paramTypes, args, pos):
        return "math.e" 
Example #17
Source Project: raveberry   Author: raveberry   File: programs.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, lights: "Lights") -> None:
        super().__init__(lights)
        self.name = "Rave"
        self.cava = self.lights.cava_program

        # RING
        # map the leds to rainbow colors from red over green to blue
        # (without pink-> hue values in [0, ⅔]
        # stretch the outer regions (red and blue) and compress the inner region (green)
        self.led_count = self.lights.ring.LED_COUNT
        hues = [
            (2 / 3)
            * 1
            / (1 + math.e ** (-4 * math.e * (led / (self.led_count - 1) - 0.5)))
            for led in range(0, self.led_count)
        ]
        self.base_colors = [colorsys.hsv_to_rgb(hue, 1, 1) for hue in hues]

        # STRIP
        # distribute frequencies over the three leds. Don't use hard cuts, but smooth functions
        # the functions add up to one at every point and each functions integral is a third
        self.red_coeffs = [
            -1 / (1 + math.e ** (-6 * math.e * (led / (self.led_count - 1) - 1 / 3)))
            + 1
            for led in range(0, self.led_count)
        ]
        self.blue_coeffs = [
            1 / (1 + math.e ** (-6 * math.e * (led / (self.led_count - 1) - 2 / 3)))
            for led in range(0, self.led_count)
        ]
        self.green_coeffs = [
            1 - self.red_coeffs[led] - self.blue_coeffs[led]
            for led in range(0, self.led_count)
        ]

        self.current_frame: List[float] = [] 
Example #18
Source Project: raveberry   Author: raveberry   File: programs.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def compute(self) -> None:
        """If active, read output from the cava program.
        Make sure that the most recent frame is always fully available,
        Stores incomplete frames for the next update."""
        # do not compute if no program uses cava
        if self.consumers == 0:
            return
        # read the fifo until we get to the current frame
        while True:
            try:
                read = os.read(
                    self.cava_fifo, self.frame_length - len(self.growing_frame)
                )
                if read == b"":
                    return
                self.growing_frame += read
            except OSError as e:
                if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
                    # there were not enough bytes for a whole frame, keep the old frame
                    return

            # we read a whole frame, update the factors
            if len(self.growing_frame) == self.frame_length:
                # vol = max(0.01, self.lights.base.musiq.player.volume)
                # self.current_frame = [int(b) / 255 / vol for b in self.growing_frame]
                self.current_frame = [int(b) / 255 for b in self.growing_frame]
                self.growing_frame = b"" 
Example #19
Source Project: vj4   Author: vijos   File: difficulty.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _LOGP(x: float):
  sqrt_2_pi = 2.506628274631000502415765284811 # math.sqrt(2 * math.pi)
  return math.exp(-1.0 * pow(math.log(x, math.e), 2) / 0.5) / x / 0.5 / sqrt_2_pi 
Example #20
Source Project: appmetrics   Author: avalente   File: statistics.py    License: Apache License 2.0 5 votes vote down vote up
def geometric_mean(data):
    """Return the geometric mean of data
    """

    if not data:
        raise StatisticsError('geometric_mean requires at least one data point')

    # in order to support negative or null values
    data = [x if x > 0 else math.e if x == 0 else 1.0 for x in data]

    return math.pow(math.fabs(functools.reduce(operator.mul, data)), 1.0 / len(data)) 
Example #21
Source Project: lambda-packs   Author: ryfeus   File: normal.py    License: MIT License 5 votes vote down vote up
def _entropy(self):
    # Use broadcasting rules to calculate the full broadcast scale.
    scale = self.scale * array_ops.ones_like(self.loc)
    return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(scale) 
Example #22
Source Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    License: Apache License 2.0 5 votes vote down vote up
def test_float(self):
        # only almost equal: double -> float -> double
        import math
        self.check_type(c_float, math.e)
        self.check_type(c_float, -math.e) 
Example #23
Source Project: ironpython2   Author: IronLanguages   File: test_callbacks.py    License: Apache License 2.0 5 votes vote down vote up
def test_callback_register_int(self):
        # Issue #8275: buggy handling of callback args under Win64
        # NOTE: should be run on release builds as well
        dll = CDLL(_ctypes_test.__file__)
        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
        # All this function does is call the callback with its args squared
        func = dll._testfunc_cbk_reg_int
        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
        func.restype = c_int

        def callback(a, b, c, d, e):
            return a + b + c + d + e

        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6)) 
Example #24
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testConstants(self):
        self.ftest('pi', math.pi, 3.1415926)
        self.ftest('e', math.e, 2.7182818) 
Example #25
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testExp(self):
        self.assertRaises(TypeError, math.exp)
        self.ftest('exp(-1)', math.exp(-1), 1/math.e)
        self.ftest('exp(0)', math.exp(0), 1)
        self.ftest('exp(1)', math.exp(1), math.e)
        self.assertEqual(math.exp(INF), INF)
        self.assertEqual(math.exp(NINF), 0.)
        self.assertTrue(math.isnan(math.exp(NAN))) 
Example #26
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testLog1p(self):
        self.assertRaises(TypeError, math.log1p)
        self.ftest('log1p(1/e -1)', math.log1p(1/math.e-1), -1)
        self.ftest('log1p(0)', math.log1p(0), 0)
        self.ftest('log1p(e-1)', math.log1p(math.e-1), 1)
        self.ftest('log1p(1)', math.log1p(1), math.log(2))
        self.assertEqual(math.log1p(INF), INF)
        self.assertRaises(ValueError, math.log1p, NINF)
        self.assertTrue(math.isnan(math.log1p(NAN)))
        n= 2**90
        self.assertAlmostEqual(math.log1p(n), 62.383246250395075)
        self.assertAlmostEqual(math.log1p(n), math.log1p(float(n))) 
Example #27
Source Project: auto-alt-text-lambda-api   Author: abhisuri97   File: normal.py    License: MIT License 5 votes vote down vote up
def _entropy(self):
    # Use broadcasting rules to calculate the full broadcast sigma.
    sigma = self.sigma * array_ops.ones_like(self.mu)
    return 0.5 * math.log(2. * math.pi * math.e) + math_ops.log(sigma) 
Example #28
Source Project: GraphEmbedding   Author: shenweichen   File: walker.py    License: MIT License 5 votes vote down vote up
def _exec_random_walk(self, graphs, layers_accept, layers_alias, v, walk_length, gamma, stay_prob=0.3):
        initialLayer = 0
        layer = initialLayer

        path = []
        path.append(self.idx2node[v])

        while len(path) < walk_length:
            r = random.random()
            if(r < stay_prob):  # same layer
                v = chooseNeighbor(v, graphs, layers_alias,
                                   layers_accept, layer)
                path.append(self.idx2node[v])
            else:  # different layer
                r = random.random()
                try:
                    x = math.log(gamma[layer][v] + math.e)
                    p_moveup = (x / (x + 1))
                except:
                    print(layer, v)
                    raise ValueError()

                if(r > p_moveup):
                    if(layer > initialLayer):
                        layer = layer - 1
                else:
                    if((layer + 1) in graphs and v in graphs[layer + 1]):
                        layer = layer + 1

        return path 
Example #29
Source Project: pyth   Author: isaacg1   File: macros.py    License: MIT License 5 votes vote down vote up
def end(a):
    if isinstance(a, complex):
        return a.imag
    if is_num(a):
        return a % 10
    if is_seq(a):
        return a[-1]
    return unknown_types(end, "e", a) 
Example #30
Source Project: pyth   Author: isaacg1   File: macros.py    License: MIT License 5 votes vote down vote up
def divmod_or_delete(a, b):
    if is_num(a) and is_num(b):
        return list(divmod(a, b))
    elif is_seq(a) and is_num(b):
        return divmod_or_delete(a, [b])
    elif is_seq(a) and is_col(b):
        output = [e for i, e in enumerate(a) if i not in b]
        if isinstance(a, str):
            return "".join(output)
        return output
    return unknown_types(divmod_or_delete, '.D', a, b)