# NumPy 陣列資料型態

``````n = 128

xs = []
ys = []
for y in range(n):
for x in range(n):
if x & y == 0:
xs.append(x)
ys.append(y)
``````

``````n = 128

xs = []
for y in range(n):
for x in range(n):
if x & y == 0:
xs.append(x)

ys = []
for y in range(n):
for x in range(n):
if x & y == 0:
ys.append(x)
``````

``````n = 128

xs = []
for elem in range(n ** 2):
x = elem // n
y = elem % n
if x & y == 0:
xs.append(x)

ys = []
for elem in range(n):
x = elem // n
y = elem % n
if x & y == 0:
ys.append(x)
``````

``````n = 128

nums = []
for num in range(n ** 2):
x = num // n
y = num % n
if x & y == 0:
nums.append(num)

xs = [num // n for num in nums]
ys = [num % n for num in nums]
``````

``````def quotientAndRemainderZero(elem, n):
quotient = elem // n
remainder = elem % n
return quotient & remainder == 0

quotientAndRemainderZero = np.frompyfunc(quotientAndRemainderZero, 2, 1)
``````

``````n = 128
nums = np.arange(n ** 2)
nums = nums[quotientAndRemainderZero(nums, n)]
``````

``````IndexError: arrays used as indices must be of integer (or boolean) type
``````

``````>>> import numpy as np
>>> a1 = np.array([1, 2, 3])
>>> a1.dtype
dtype('int32')
>>> a2 = np.array([1.1, 2.1, 3.1])
>>> a2.dtype
dtype('float64')
>>> a3 = np.array([True, False])
>>> a3.dtype
dtype('bool')
>>>
``````

``````n = 128
nums = np.arange(n ** 2)
nums = nums[quotientAndRemainderZero(nums, n).astype(np.bool)]
``````

``````>>> a = np.array([10, 20, 30])
>>> np.where(a > 10, a, a * 10)
array([100,  20,  30])
>>> np.where(a > 10)
(array([1, 2], dtype=int64),)
>>>
``````

`where` 的第一個參數接受布林陣列，如果元素是 `True`，選擇第二個參數指定陣列對應位置的值，否則選擇第三個參數指定陣列對應位置的值，如果只指定第一個參數，傳回 `True` 元素的索引。

``````n = 128
nums = np.arange(n ** 2)
nums = nums[np.where(quotientAndRemainderZero(nums, n))]
``````

``````import numpy as np
import matplotlib.pyplot as plt

def scatter_plot(title, plotsize, axislim, markersize, xs, ys):
plt.title(title)
plt.gcf().set_size_inches(plotsize)
plt.xlim(axislim)
plt.ylim(axislim)
plt.xlabel('x')
plt.ylabel('y')
plt.scatter(xs, ys, marker = 's', s = markersize ** 2)
plt.show()

def sierpinski(n):
def quotientAndRemainderZero(elem, n):
quotient = elem // n
remainder = elem % n
return quotient & remainder == 0

quotientAndRemainderZero = np.frompyfunc(quotientAndRemainderZero, 2, 1)

nums = np.arange(n ** 2)
nums = nums[np.where(quotientAndRemainderZero(nums, n))]
return (nums % n, nums // n)

n = 128
x, y = sierpinski(n)

plotwidth = 6
axislim = (-0.5, n - 0.5)
plotsize = (plotwidth, plotwidth)
PTS_PER_INCH = 72
plotwidth_pts = PTS_PER_INCH * plotwidth
marksize = 0.775 * plotwidth_pts / n

scatter_plot(
'Sierpinski triangle',
plotsize,
axislim,
marksize,
x,
y
)
``````