How do I do exponentiation in python?
^
is the xor operator.
**
is exponentiation.
2**3 = 8
Negative numbers with exponents in Python
Python parses print(-1**2)
in the following order:
Get's the exponent of
1 ** 2
Negates the result.
So it becomes this:
>>> -(1 ** 2)
-1
>>>
Because -1
translates to print(0 - 1 ** 2)
. But in the order of operations table, **
(exponents) is higher ranking than -
.
Therefore, Python math follows the order of operations in regular math, **
is more powerful (has more priority over) -
.
As mentioned on Wikipedia:
The acronym PEMDAS is common. It stands for Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.
Also mentioned on the Python Docs:
Operator | Description |
---|---|
(expressions...), [expressions...], {key: value...}, {expressions...} | Binding or parenthesized expression, list display, dictionary display, set display |
x[index], x[index:index], x(arguments...), x.attribute | Subscription, slicing, call, attribute reference |
await x | Await expression |
** | Exponentiation |
+x, -x, ~x | Positive, negative, bitwise NOT |
*, @, /, //, % | Multiplication, matrix multiplication, division, floor division, remainder 6 |
Exponentiate a number N times in Python?
So you want to calculate base ** (exponent ** n)
, and since the operator **
already binds right to left, we can skip the brackets:
def exponentiate_n_times(base, exponent, n):
return base ** exponent ** n
exponentiate_n_times(2, 2, 3) # 256
exponentiate_n_times(3, 2, 3) # 6561
exponentiate_n_times(3, 3, 3) # 7625597484987
Exponentiation in Python - should I prefer ** operator instead of math.pow and math.sqrt?
math.sqrt
is the C implementation of square root and is therefore different from using the **
operator which implements Python's built-in pow
function. Thus, using math.sqrt
actually gives a different answer than using the **
operator and there is indeed a computational reason to prefer numpy
or math
module implementation over the built-in. Specifically the sqrt functions are probably implemented in the most efficient way possible whereas **
operates over a large number of bases and exponents and is probably unoptimized for the specific case of square root. On the other hand, the built-in pow
function handles a few extra cases like "complex numbers, unbounded integer powers, and modular exponentiation".
See this Stack Overflow question for more information on the difference between **
and math.sqrt
.
In terms of which is more "Pythonic", I think we need to discuss the very definition of that word. From the official Python glossary, it states that a piece of code or idea is Pythonic if it "closely follows the most common idioms of the Python language, rather than implementing code using concepts common to other languages." In every single other language I can think of, there is some math module with basic square root functions. However there are languages that lack a power operator like **
e.g. C++. So **
is probably more Pythonic, but whether or not it's objectively better depends on the use case.
Creating a function to print the exponents without using **
As we all know, pow is just repeated multiplication.
So, we can create a loop that on every iteration it'll multiply a variable (we'll declare a variable that his starting value is 1) by 2.
Example code:
powers = 1 # Declare variable.
for pow in range(10): # Set a loop for range(10).
print(powers) # Print the variable.
powers *= 2 # Power it by 2.
How does Python calculate exponents?
The **
operator translates to the BINARY_POWER
opcode in the bytecode, which the interpreter then translates to the C-API PyNumber_Power
call with the 3rd argument set to None.
PyNumber_Power
calls the nb_power
slot on the operands (see ternary_op
).
If both are integers, the int_pow
C function succeeds and its result used.
If however x
is an integer and you use 2.3
as the power, the integer power function raises an error and float_pow
is tried next. In that case, provided x
is greater than 0, the C library pow()
function is used on two float values, which on most architectures is then handled by the floating point support in the CPU.
Related Topics
Get a Function Argument's Default Value
Is a Python Dictionary an Example of a Hash Table
Get Lat/Long Given Current Point, Distance and Bearing
What Does a for Loop Within a List Do in Python
Download File Through Google Chrome in Headless Mode
How to Convert a Time.Struct_Time Object into a Datetime Object
How to Dynamically Create Derived Classes from a Base Class
How to Plot a Gradient Color Line in Matplotlib
Importerror: No Module Named _Ssl
Cumsum as a New Column in an Existing Pandas Data
Split a String with Unknown Number of Spaces as Separator in Python
Pip Installing in Global Site-Packages Instead of Virtualenv
Get Fully Qualified Class Name of an Object in Python
How to Start and Stop a Thread
How to Set Up a Virtual Environment for Python in Visual Studio Code
How to Send Cookies in a Post Request with the Python Requests Library
How to Find the Groups of Consecutive Elements in a Numpy Array