57

How can I write 1-e^(-value1^2/2*value2^2) in Python?

I don't know how to use power operator and e.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Thanos Smar
  • 631
  • 1
  • 8
  • 12

7 Answers7

66

You can use exp(x) function of math library, which is same as e^x. Hence you may write your code as:

import math
x.append(1 - math.exp( -0.5 * (value1*value2)**2))

I have modified the equation by replacing 1/2 as 0.5. Else for Python <2.7, we'll have to explicitly type cast the division value to float because Python round of the result of division of two int as integer. For example: 1/2 gives 0 in python 2.7 and below.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
21

Python's power operator is ** and Euler's number is math.e, so:

 from math import e
 x.append(1-e**(-value1**2/2*value2**2))
karlosss
  • 2,816
  • 7
  • 26
  • 42
21

Just saying: numpy has this too. So no need to import math if you already did import numpy as np:

>>> np.exp(1)
2.718281828459045
gosuto
  • 5,422
  • 6
  • 36
  • 57
  • 1
    The Numpy version has the advantage of using vectorisation when using Numpy arrays. – Leo May 12 '22 at 11:12
6

Power is ** and e^ is math.exp:

x.append(1 - math.exp(-0.5 * (value1*value2)**2))
Daniel
  • 42,087
  • 4
  • 55
  • 81
3

math.e or from math import e (= 2.718281…)

The two expressions math.exp(x) and e**x are equivalent however:
Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x). docs.python

for power use ** (3**2 = 9), not " ^ "
" ^ " is a bitwise XOR operator (& and, | or), it works logicaly with bits. So for example 10^4=14 (maybe unexpectedly) → consider the bitwise depiction:

(0000 1010 ^ 0000 0100 = 0000 1110) programiz

Cadoiz
  • 1,446
  • 21
  • 31
Alexey K.
  • 101
  • 4
1

Just to add, numpy also has np.e

Rik Mulder
  • 245
  • 1
  • 9
1

In my case, the exponent happens to be complex number with angle expressed in radians. So my approach was:

import cmath 
theta = cmath.pi/4
output = cmath.exp(theta*1j)   # LaTeX: $e^{i\theta}$ 
print(output)                  # (0.7071067811865476+0.7071067811865476j)

Note: Use 1j instead of j since python throws NameError for j. And used cmath instead of math.

Rajesh Swarnkar
  • 601
  • 1
  • 6
  • 18