昨天读可爱的 Python: Numerical Python就觉得这个地方不对:
near_fireplace = north[2:4,2:5]
动手试试发现应该是
near_fireplace = north[2:4,1:4]
然后又仔细研究了一下均温函数,笔记如下:
# See 可爱的 Python: Numerical Python:
# Url: http://www-128.ibm.com/developerworks/cn/linux/l-cpnum/
from numarray import *
room = zeros((4,3,5), Float)
room += 70
floor = room[3]
floor -= 4
# Slice operation start:stop:step,start:stop:step,start:stop:step,...
# Dimension first(4): : - from 0 to 3
# Dimension seperator: ,
# Dimension second(3): 0, Ignore stop and step means to default the last index and 1
# Dimension third((5): Ignore means all
# north = room[,0] is an error syntax
north = room[:,0]
north[3,2] = 90 # the fireplace cell itself
# Wrong in article : near_fireplace = north[2:4,2:5]
near_fireplace = north[2:4,1:4]
near_fireplace += 8
# 平均温度
# add.reduce alias as sum
add.reduce(room.flat)/len(room.flat)
def equalize(room):
from random import randint
# 随机挑选一个点(x,y,z)
# room.shape == (4,3,5)
# z [1,4]
# y [1,3]
# x[1,5]
z,y,x = map(randint, (1,1,1), room.shape)
# zmin,ymin,xmin = maximum([z-2,y-2,x-2],[0,0,0]) isOK?
# zmin [0,2]
# ymin [0,1]
# xmin [0, 3]
zmin,ymin,xmin = maximum([z-2,y-2,x-2],[0,0,0]).tolist()
# Overflow? Maybe... But as a stop index, it does NOT matter.
# zmax [1,5]
# ymax [1,4]
# xmax [1, 6]
zmax,ymax,xmax = [z+1,y+1,x+1]
# 得到一个气流块
# 边界条件
# ( Wrong thinking :P
# ?max = ?min + 3
# room[0:5, 0:4, 0:6] == room <- Wrong
#
# room[2:1, 1:1, 3:1] is array([], shape=(0, 0, 0), type=Float) <- Wrong
# sum(region) will be 0.0
# len(region) will be 0
# Bingo! we got "ZeroDivisionError: float division" before return!
# )
region = room[zmin:zmax,ymin:ymax,xmin:xmax].copy()
# why NOT room[z, y, x]? Because
# room[4, 3, 5] -> IndexError: Index out of range
room[z-1,y-1,x-1] = sum(region.flat)/len(region.flat)
return room
equalize(room.copy())
# Todo: Visualize Unit 8
# rgb (255, 0, 0) Hot >30C(80F)
# rgb (0, 255, 0) Warm 0 - 30(50F - 80F)
# rgb (0, 0, 255) Cold <0C(50F)
这说明动手的重要性,另:有机会可视化一下。
Technorati : NumPy, Python