Python3中運算符 **和*的區別

我們知道**代表次方。

如下
>>>12 * 12
144
>>>12 ** 2
144


>>>a=1e200
>>> a
1e+200
>>>a ** 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
>>>a * a
inf
>>>a = 100 ** 100  # python3中int整型一般不會溢出,取決於內存
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
>>>a * a,a ** 2   # 兩種方式都沒問題,int很大,不會溢出,取決於內存
(10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
>>>float(a) * float(a)    #float用這種方法,也不會溢出
inf
>>>float(a) ** 2  #float用這種方式有可能溢出,注意!!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: (34, 'Result too large')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章