NumPy の浮動小数点数が np.float64 と表示される問題

今年度から新しい JupyterHub を授業で使うようになって気づいたところ。

数学関数を使う

math

In [1]:
import math
In [2]:
math.pi
Out[2]:
3.141592653589793

$\sin \dfrac{\pi}{2}, \cos \dfrac{\pi}{3}, \tan\dfrac{\pi}{4}$ の値を一気に表示

In [3]:
math.sin(math.pi/2), math.cos(math.pi/3), math.tan(math.pi/4)
Out[3]:
(1.0, 0.5000000000000001, 0.9999999999999999)

NumPy

In [4]:
import numpy as np    # np. をつけて使う
In [5]:
np.pi
Out[5]:
3.141592653589793

NumPy でも $\sin \dfrac{\pi}{2}, \cos \dfrac{\pi}{3}, \tan\dfrac{\pi}{4}$ の値を一気に表示させたいのだが…

In [6]:
np.sin(np.pi/2), np.cos(np.pi/3), np.tan(np.pi/4)
Out[6]:
(np.float64(1.0),
 np.float64(0.5000000000000001),
 np.float64(0.9999999999999999))

np.float64 っていうのがつくんだけど…

この現象の原因は,NumPy 2.0 以降で表示方法が変更されたことにある。

なので,以前の旧 弘大 JupyterHub のような表示にしたければ,以下のように数値の表示形式を変更しておくことで対応できる。

In [7]:
np.set_printoptions(legacy='1.25') 
In [8]:
np.sin(np.pi/2), np.cos(np.pi/3), np.tan(np.pi/4)
Out[8]:
(1.0, 0.5000000000000001, 0.9999999999999999)