How to do C language calculation in Python - python

I want to do some simulation of C language calculation in Python.
For example, unsigned short, single precision float ...
ushort(0xffff) + 1 -> 0
0.1f * 0.1f -> ...
Are there some library to do this in Python?
I can use ctypes to create unsigned short, single float, but they
cann't do math operation:
a = c_uint16(0xffff)
b = c_uint16(0x01)
a+b -> TypeError
Or, I can use numpy:
>>> np.uint16(0xffff) + np.uint16(0x01)
Warning: overflow encountered in ushort_scalars
0
but it's very slow comparing to Python's normal calculation:
>>> timeit.timeit("a+b", "import numpy as np;a=np.uint16(0xfffe);b=np.uint16(0x01)")
0.35577465681618037
>>> timeit.timeit("0xfffe+0x01")
0.022638104432360251
>>> timeit.timeit("np.uint16(0xfffe) + np.uint16(0x01)", "import numpy as np")
5.904765399236851
Edit:
>>> timeit.timeit("a+b", "a=0xfffe;b=0x01")
0.040062221014295574

When compiling 0xfffe+0x01, this will be folded into the constant 65535. You aren't timing how long the addition takes -- you are just measuring the time of loading the constant:
>>> dis.dis(compile("0xfffe+0x01", "", "eval"))
1 0 LOAD_CONST 2 (65535)
3 RETURN_VALUE
The addition of NumPy scalars is slower than adding built-in integers nevertheless, but it won't get better than that in pure Python. Consider using Cython -- it will allow you to declare types and execute the computations in C speed. Alternatively, try to vectorise your code in NumPy (that is, if speed really matters).

You can make a function for each operation using modulo % with 2**sizeof (in your case, 2**16 or 65536)
def add(a, b, mod=2**16):
return (a+b) % mod
def sub(a, b, mod=2**16):
return (a-b) % mod
and any other function you need.
>>> add(0xffff, 1)
0
>>> sub(10, 20)
65526
Note this will work only for unsigned types. For signed ones, you can use half the value used to mod (i.e. 2**15) and will have to validate the result before applying modulo

Related

Gamma function in python doesn't plot what I expected [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

How do I do a bitwise Not operation in Python?

In order to test building an Xor operation with more basic building blocks (using Nand, Or, and And in my case) I need to be able to do a Not operation. The built-in not only seems to do this with single bits. If I do:
x = 0b1100
x = not x
I should get 0b0011 but instead I just get 0b0. What am I doing wrong? Or is Python just missing this basic functionality?
I know that Python has a built-in Xor function but I've been using Python to test things for an HDL project/course where I need to build an Xor gate. I wanted to test this in Python but I can't without an equivalent to a Not gate.
The problem with using ~ in Python, is that it works with signed integers. This is also the only way that really makes sense unless you limit yourself to a particular number of bits. It will work ok with bitwise math, but it can make it hard to interpret the intermediate results.
For 4 bit logic, you should just subtract from 0b1111
0b1111 - 0b1100 # == 0b0011
For 8 bit logic, subtract from 0b11111111 etc.
The general form is
def bit_not(n, numbits=8):
return (1 << numbits) - 1 - n
Another way to achieve this, is to assign a mask like this (should be all 1's):
mask = 0b1111
Then xor it with your number like this:
number = 0b1100
mask = 0b1111
print(bin(number ^ mask))
You can refer the xor truth table to know why it works.
Python bitwise ~ operator invert all bits of integer but we can't see native result because all integers in Python has signed representation.
Indirectly we can examine that:
>>> a = 65
>>> a ^ ~a
-1
Or the same:
>>> a + ~a
-1
Ther result -1 means all bits are set. But the minus sign ahead don't allow us to directly examine this fact:
>>> bin(-1)
'-0b1'
The solution is simple: we must use unsigned integers.
First way is to import numpy or ctypes modules wich both support unsigned integers. But numpy more simplest using than ctypes (at least for me):
import numpy as np
a = np.uint8(0b1100)
y = ~x
Check result:
>>> bin(x)
'0b1100'
>>> bin(y)
'0b11110011'
And finally check:
>>> x + y
255
Unsigned integer '255' for 8-bits integers (bytes) mean the same as '-1' becouse has all bits set to 1. Make sure:
>>> np.uint8(-1)
255
And another simplest solution, not quite right, but if you want to include additional modules, you can invert all bits with XOR operation, where second argument has all bits are set to 1:
a = 0b1100
b = a ^ 0xFF
This operation will also drop most significant bit of signed integer and we can see result like this:
>>> print('{:>08b}'.format(a))
00001100
>>> print('{:>08b}'.format(b))
11110011
Finally solution contains one more operation and therefore is not optimal:
>>> b = ~a & 0xFF
>>> print('{:>08b}'.format(b))
11110011
Try this, it's called the bitwise complement operator:
~0b1100
The answers here collectively have great nuggets in each one, but all do not scale well with depending on edge cases.
Rather than fix upon an 8-bit mask or requiring the programmer to change how many bits are in the mask, simply create a mask based on input via bit_length():
def bit_not(num):
return num ^ ((1 << num.bit_length()) - 1)
string of binary can be used to preserve the left 0s, since we know that:
bin(0b000101) # '0b101'
bin(0b101) # '0b101'
This function will return string format of the NOT of input number
def not_bitwise(n):
'''
n: input string of binary number (positive or negative)
return: binary number (string format)
'''
head, tail = n.split('b')
not_bin = head+'b'+tail.replace('0','a').replace('1','0').replace('a','1')
return not_bin
Example:
In[266]: not_bitwise('0b0001101')
Out[266]: '0b1110010'
In[267]: int(not_bitwise('0b0001101'), 2)
Out[267]: 114
In[268]: not_bitwise('-0b1010101')
Out[268]: '-0b0101010'
In[269]: int(not_bitwise('-0b1010101'), 2)
Out[269]: -42
The general form given by John La Rooy, can be simplified in this way (python == 2.7 and >=3.1):
def bit_not(n):
return (1 << n.bit_length()) - 1 - n

Python: Temperature converter only works f to c, not other way around? [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

Converting to float without truncation [duplicate]

I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a / b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python 2 in the following?
c = a / b
In 3.x, the behaviour is reversed; see Why does integer division yield a float instead of another integer? for the opposite, 3.x-specific problem.
In Python 2, division of two ints produces an int. In Python 3, it produces a float. We can get the new behaviour by importing from __future__.
>>> from __future__ import division
>>> a = 4
>>> b = 6
>>> c = a / b
>>> c
0.66666666666666663
You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.
A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.
How can I force division to be floating point in Python?
I have two integer values a and b, but I need their ratio in floating point. I know that a < b and I want to calculate a/b, so if I use integer division I'll always get 0 with a remainder of a.
How can I force c to be a floating point number in Python in the following?
c = a / b
What is really being asked here is:
"How do I force true division such that a / b will return a fraction?"
Upgrade to Python 3
In Python 3, to get true division, you simply do a / b.
>>> 1/2
0.5
Floor division, the classic division behavior for integers, is now a // b:
>>> 1//2
0
>>> 1//2.0
0.0
However, you may be stuck using Python 2, or you may be writing code that must work in both 2 and 3.
If Using Python 2
In Python 2, it's not so simple. Some ways of dealing with classic Python 2 division are better and more robust than others.
Recommendation for Python 2
You can get Python 3 division behavior in any given module with the following import at the top:
from __future__ import division
which then applies Python 3 style division to the entire module. It also works in a python shell at any given point. In Python 2:
>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0
>>> 1//2.0
0.0
This is really the best solution as it ensures the code in your module is more forward compatible with Python 3.
Other Options for Python 2
If you don't want to apply this to the entire module, you're limited to a few workarounds. The most popular is to coerce one of the operands to a float. One robust solution is a / (b * 1.0). In a fresh Python shell:
>>> 1/(2 * 1.0)
0.5
Also robust is truediv from the operator module operator.truediv(a, b), but this is likely slower because it's a function call:
>>> from operator import truediv
>>> truediv(1, 2)
0.5
Not Recommended for Python 2
Commonly seen is a / float(b). This will raise a TypeError if b is a complex number. Since division with complex numbers is defined, it makes sense to me to not have division fail when passed a complex number for the divisor.
>>> 1 / float(2)
0.5
>>> 1 / float(2j)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
It doesn't make much sense to me to purposefully make your code more brittle.
You can also run Python with the -Qnew flag, but this has the downside of executing all modules with the new Python 3 behavior, and some of your modules may expect classic division, so I don't recommend this except for testing. But to demonstrate:
$ python -Qnew -c 'print 1/2'
0.5
$ python -Qnew -c 'print 1/2j'
-0.5j
c = a / (b * 1.0)
In Python 3.x, the single slash (/) always means true (non-truncating) division. (The // operator is used for truncating division.) In Python 2.x (2.2 and above), you can get this same behavior by putting a
from __future__ import division
at the top of your module.
Just making any of the parameters for division in floating-point format also produces the output in floating-point.
Example:
>>> 4.0/3
1.3333333333333333
or,
>>> 4 / 3.0
1.3333333333333333
or,
>>> 4 / float(3)
1.3333333333333333
or,
>>> float(4) / 3
1.3333333333333333
Add a dot (.) to indicate floating point numbers
>>> 4/3.
1.3333333333333333
This will also work
>>> u=1./5
>>> print u
0.2
If you want to use "true" (floating point) division by default, there is a command line flag:
python -Q new foo.py
There are some drawbacks (from the PEP):
It has been argued that a command line option to change the
default is evil. It can certainly be dangerous in the wrong
hands: for example, it would be impossible to combine a 3rd
party library package that requires -Qnew with another one that
requires -Qold.
You can learn more about the other flags values that change / warn-about the behavior of division by looking at the python man page.
For full details on division changes read: PEP 238 -- Changing the Division Operator
from operator import truediv
c = truediv(a, b)
from operator import truediv
c = truediv(a, b)
where a is dividend and b is the divisor.
This function is handy when quotient after division of two integers is a float.

Exponentials in python: x**y vs math.pow(x, y)

Which one is more efficient using math.pow or the ** operator? When should I use one over the other?
So far I know that x**y can return an int or a float if you use a decimal
the function pow will return a float
import math
print( math.pow(10, 2) )
print( 10. ** 2 )
Using the power operator ** will be faster as it won’t have the overhead of a function call. You can see this if you disassemble the Python code:
>>> dis.dis('7. ** i')
1 0 LOAD_CONST 0 (7.0)
3 LOAD_NAME 0 (i)
6 BINARY_POWER
7 RETURN_VALUE
>>> dis.dis('pow(7., i)')
1 0 LOAD_NAME 0 (pow)
3 LOAD_CONST 0 (7.0)
6 LOAD_NAME 1 (i)
9 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
12 RETURN_VALUE
>>> dis.dis('math.pow(7, i)')
1 0 LOAD_NAME 0 (math)
3 LOAD_ATTR 1 (pow)
6 LOAD_CONST 0 (7)
9 LOAD_NAME 2 (i)
12 CALL_FUNCTION 2 (2 positional, 0 keyword pair)
15 RETURN_VALUE
Note that I’m using a variable i as the exponent here because constant expressions like 7. ** 5 are actually evaluated at compile time.
Now, in practice, this difference does not matter that much, as you can see when timing it:
>>> from timeit import timeit
>>> timeit('7. ** i', setup='i = 5')
0.2894785532627111
>>> timeit('pow(7., i)', setup='i = 5')
0.41218495570683444
>>> timeit('math.pow(7, i)', setup='import math; i = 5')
0.5655053168791255
So, while pow and math.pow are about twice as slow, they are still fast enough to not care much. Unless you can actually identify the exponentiation as a bottleneck, there won’t be a reason to choose one method over the other if clarity decreases. This especially applies since pow offers an integrated modulo operation for example.
Alfe asked a good question in the comments above:
timeit shows that math.pow is slower than ** in all cases. What is math.pow() good for anyway? Has anybody an idea where it can be of any advantage then?
The big difference of math.pow to both the builtin pow and the power operator ** is that it always uses float semantics. So if you, for some reason, want to make sure you get a float as a result back, then math.pow will ensure this property.
Let’s think of an example: We have two numbers, i and j, and have no idea if they are floats or integers. But we want to have a float result of i^j. So what options do we have?
We can convert at least one of the arguments to a float and then do i ** j.
We can do i ** j and convert the result to a float (float exponentation is automatically used when either i or j are floats, so the result is the same).
We can use math.pow.
So, let’s test this:
>>> timeit('float(i) ** j', setup='i, j = 7, 5')
0.7610865891750791
>>> timeit('i ** float(j)', setup='i, j = 7, 5')
0.7930400942188385
>>> timeit('float(i ** j)', setup='i, j = 7, 5')
0.8946636625872202
>>> timeit('math.pow(i, j)', setup='import math; i, j = 7, 5')
0.5699394063529439
As you can see, math.pow is actually faster! And if you think about it, the overhead from the function call is also gone now, because in all the other alternatives we have to call float().
In addition, it might be worth to note that the behavior of ** and pow can be overridden by implementing the special __pow__ (and __rpow__) method for custom types. So if you don’t want that (for whatever reason), using math.pow won’t do that.
The pow() function will allow you to add a third argument as a modulus.
For example: I was recently faced with a memory error when doing
2**23375247598357347582 % 23375247598357347583
Instead I did:
pow(2, 23375247598357347582, 23375247598357347583)
This returns in mere milliseconds instead of the massive amount of time and memory that the plain exponent takes. So, when dealing with large numbers and parallel modulus, pow() is more efficient, however when dealing with smaller numbers without modulus, ** is more efficient.
Just for the protocol: The ** operator is equivalent to the two-argument version of the built-in pow function, the pow function accepts an optional third argument (modulus) if the first two arguments are integers.
So, if you intend to calculate remainders from powers, use the built-in function. The math.pow will give you false results for arguments of reasonable size:
import math
base = 13
exp = 100
mod = 2
print math.pow(base, exp) % mod
print pow(base, exp, mod)
When I ran this, I got 0.0 in the first case which obviously cannot be true, because 13 is odd (and therefore all of it's integral powers). The math.pow version uses the limited accuracy of the IEEE-754 Double precision (52 bits mantissa, slightly less than 16 decimal places) which causes an error here.
For sake of fairness, we must say, math.pow can also be faster:
>>> import timeit
>>> min(timeit.repeat("pow(1.1, 9.9)", number=2000000, repeat=5))
0.3063715160001266
>>> min(timeit.repeat("math.pow(1.1, 9.9)", setup="import math", number=2000000, repeat=5))
0.2647279420000359
The math.pow function had (and still has) its strength in engineering applications, but for number theoretical applications, you should use the built-in pow function.
Some online examples
http://ideone.com/qaDWRd (wrong remainder with math.pow)
http://ideone.com/g7J9Un (lower performance with pow on int values)
http://ideone.com/KnEtXj (slightly lower performance with pow on float values)
Update (inevitable correction):
I removed the timing comparison of math.pow(2,100) and pow(2,100) since math.pow gives a wrong result whereas, for example, the comparison between pow(2,50) and math.pow(2,50) would have been fair (although not a realistic use of the math-module function). I added a better one and also the details that cause the limitation of math.pow.
** is indeed faster then math.pow(), but if you want a simple quadratic function like in your example it is even faster to use a product.
10.*10.
will be faster then
10.**2
The difference is not big and not noticable with one operation (using timeit), but with a large number of operations it can be significant.
Well, they are for different tasks, really.
Use pow (equivalent to x ** y with two arguments) when you want integer arithmetic.
And use math.pow if either argument is float, and you want float output.
For a discussion on the differences between pow and math.pow, see this question.
operator ** (same as pow()) can be used to calculate very large integer number.
>>> 2 ** 12345
164171010688258216356020741663906501410127235530735881272116103087925094171390144280159034536439457734870419127140401667195510331085657185332721089236401193044493457116299768844344303479235489462...
>>> math.pow(2, 12345)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: math range error
For small powers, like 2, I prefer to just multiply the base:
Use x*x instead of x**2 or pow(x, 2).
I haven't timed it, but I'd bet the multiplier is as fast as either the exponential operator or the pow function.

Categories