# 如何在 Python 中進行冪運算

Python 提供了內建的操作和函式來幫助執行冪運算。

## 在 Python 中使用`**`運算子來進行冪運算

``````print(5 ** 6)
``````

``````15625
``````

``````num1 = 2
num2 = -5
num3 = 0
num4 = 1.025
num5 = 0.5

print(num1, "^12=", num1 ** 12)
print(num2, "^4=", num2 ** 4)
print(num3, "^9999=", num3 ** 9999)
print(num4, "^-3=", num4 ** -3)
print(num5, "^8=", num5 ** 8)
``````

``````2^12= 4096
-5^4= 625
0^9999= 0
1.025^-3= 0.928599410919749
0.5^8= 0.00390625
``````

## 在 Python 中使用 `pow()` 或 `math.power()` 做指數運算

``````import math

print(pow(-8, 7))
print(math.pow(-8, 7))

print(pow(2, 1.5))
print(math.pow(2, 1.5))

print(pow(4, 3))
print(math.pow(4, 3))

print(pow(2.0, 5))
print(math.pow(2.0, 5))
``````

``````-2097152
-2097152.0
2.8284271247461903
2.8284271247461903
64
64.0
32.0
32.0
``````

## 在 Python 中使用 `numpy.np()` 做指數運算

• Python 2：
``````pip install numpy
``````
• Python 3:
``````pip3 install numpy
``````

``````print(np.power(-8, 7))
print(np.power(2, 1.5))
print(np.power(4, 3))
print(np.power(2.0, 5))
``````

``````-2097152
2.8284271247461903
64
32.0
``````

`power()` 產生的輸出和內建的 Python 函式 `pow()` 一樣，如果沒有 `float` 引數，它將返回一個整數。

## 比較每個解決方案的執行時間

``````import numpy as np
import math
import time

start = time.process_time()
val = 2 ** 99999
print("** took", time.process_time() - start, "ms")

start = time.process_time()
val = pow(2, 99999)
print("pow() took", time.process_time() - start, "ms")

start = time.process_time()
val = np.power(2, 99999)
print("np.power() took", time.process_time() - start, "ms")

start = time.process_time()
val = math.pow(2, 99999)
print("math.pow() took", time.process_time() - start, "ms")
``````

``````** took 0.0006959999999999744 ms

pow() took 0.00039000000000000146 ms

np.power() took 1.6999999999989246e-05 ms

Traceback (most recent call last):
File "/Users/rayven/python/timeit.py", line 15, in <module>
val = math.pow(2,99999)
OverflowError: math range error
``````

``````** took 1.0000000000010001e-05 ms
pow() took 4.000000000004e-06 ms
np.power() took 2.0000000000020002e-05 ms
math.pow() took 2.9999999999752447e-06 ms
``````

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.