
我正在運行 Ubuntu 14.10,而且我對 Python 完全陌生。
我知道Python可以在交互模式下用作CLI類型計算器,有點像Bash中的bc指令。
我有兩個問題:
如何設定計算答案的小數位數
我需要做什麼才能使用
sqrt
,sin
,arcos
,等數學函數log
每當我嘗試使用這些函數中的任何一個時,我都會收到一條錯誤訊息,例如:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sin' is not defined
答案1
1)如何設定計算答案的小數位數
對於浮點運算(在 python2 中),您必須使用浮點數而不是整數,請參閱:
>>> 3/2
1
>>> 3/2.0
1.5
>>> 3.0/2
1.5
如果您使用的是 python3,那麼結果是浮動的,即使兩個運算元都是整數:
Python 3.4.2 (default, Oct 8 2014, 13:08:17) [GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1.5
>>> 3/3
1.0
若要在 python3 中執行整數除法,請使用//
運算子:
>>> 3//2
1
>>> 3//3
1
2)我需要做什麼才能使用 sqrt、sin、arcos、log 等數學函數
這些函數位於數學模組中,使用它們的最簡單方法是:
>>> from math import *
>>> sqrt(4)
2.0
但要小心,因為它可能會污染您的名稱空間(如果存在與math
模組中名稱相同的變數或函數)。使用更安全:
>>> import math
>>> math.sqrt(4)
2.0