2012年3月12日月曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のI部(Pythonの基礎知識)5章(数値)の問題を解いてみる。

1, 2, 3.

それぞれ演算結果は、14、10、14となる。

4.

ある数の平方根、平方を求めるのに使用出来るツールはmathモジュールのsqrt関数とpow関数。(平方は演算子**でも求められる。)

5.

1+2.0+3という演算子の結果はfloat型(浮動小数点数型)になる。

6.

浮動小数点数の切り捨てにはmathモジュールのfloor関数(この場合は浮動小数点数のまま)、あるいはintに変換、丸めを行うには、round関数を使用すればいい。

7.

整数を浮動小数点数に変換するには、float関数を使用すればいい。(あるいは0.0(浮動小数点数)を加えるなどして浮動小数点にする方法もある。)

8.

整数を8進数、16進数で表示するにはそれぞれoct関数、hex関数を使用すればいい。

9.

8進数、16進数を通常の整数に変換するには、int関数の第2引数にそれぞれ基数8, 16を指定すればいい。

それぞれの問題の解答を確認。

入出力結果(Terminal)

$ python
Python 2.7.2 (default, Feb 12 2012, 23:50:38) 
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2*(3+4)
14
>>> 2*3+4
10
>>> 2+3*4
14
>>> n=2
>>> import math
>>> math.sqrt(n)
1.4142135623730951
>>> math.pow(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pow expected 2 arguments, got 1
>>> math.pow(n,2)
4.0
>>> n**2
4
>>> 1+2.0+3
6.0
>>> typeof(6.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'typeof' is not defined
>>> int(6.0)
6
>>> math.floor(6.0)
6.0
>>> round(6.5)
7.0
>>> round(6.4)
6.0
>>> int(6.5)
6
>>> math.floor(6.5)
6.0
>>> float(5)
5.0
>>> n=5
>>> n=n+0.0
>>> n
5.0
>>> oct(8)
'010'
>>> hex(8)
'0x8'
>>> oct(16)
'020'
>>> hex(16)
'0x10'
>>> int(020,8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() can't convert non-string with explicit base
>>> int('020',8)
16
>>> int('0x10',16)
16
>>> int('020')
20
>>> int('010',8)
8
>>> int('0x8',16)
8
>>> quit()
$

0 コメント:

コメントを投稿