Search

Python Pow() function For Python Power

The python pow() function, most times called python power function, is a built-in function for calculating the power of a number when raised to an exponent. It comes in very handy several times while doing mathematical operations.

python pow() function

 

The syntax of the python power function is pow(base, exp[, mod]) where base is the number whose power you are looking for, exp is the exponent to which you will raise the base or number, and the optional mod is a modulus integer you might wish to use for the result. In simple terms, it returns the base to the power of the exp.

This is a very simple function to use. In fact, it is one of the simplest I have found in the built-in python functions.

Let’s illustrate its usage with examples.

1. When base is positive and exp is positive.

This is simply the act of raising the base, or number, to the exponent, exp. In literal terms, base ** exp. Consider the example below:

The base is 4 and the exponent is 2. So 4 raised to power 2 gives 16. Very easy to read.

2. When base is negative and the exp is positive.

This is similar to the above. Just raise the base to the exponent.

3. When base is positive or negative but the exponent is negative.

In this case, when the exponent is negative, the result is no longer an int type but a floating point type. Note this difference.

This is correspondent to when you are raising fractions by an exponent. That is why I so love python. You can use it to do so many different things. It gives just the right results for any calculation you assign to it.

4. When you use it with the three arguments, pow(base, exp, mod)

When you use the third optional argument, mod, which means modulus, you are doing an operation which takes the modulus of the result from raising the base by the exponent. Let us illustrate with some examples:

In the above code this is what is happening. The pow() function first raises 4 to the power of 2, the exponent. The result is 16. Then it does 16 modulus 5 which is 1. That’s it.

Do you know that you can even do the modulus of fractional results? Yes, this function gives you the power to do that. Let’s illustrate by raising 4 by negative 2, -2, and get the modulus by 5.

    
base = 4
exp = -2
modulus = 5
n = pow(base, exp, modulus)
print(n)

This new power was introduced in python 3.8. The embedded python interpreter is upgraded only to python 3.6. So, you can run it on your machine and see that 4 raised to the power of negative 2, -2, is 0.0625 and when modulus 5 is called on the result it gives 1.

That’s it. I had a swell time introducing you to this powerful python power function. Play and use it to your heart’s delight. Leave a comment about your findings. I would love to see some comments about this powerful function.

Happy pythoning.

No comments:

Post a Comment

Your comments here!

Matched content