首页 > 解决方案 > 对矩阵应用运算时结果不正确

问题描述

我正在尝试通过将 a 转换为图像来制作圆形numpy matrix图像,但是当输入为50或更多时,图像上出现奇怪的缺失线条。我怎样才能解决这个问题?

输入决定矩阵的大小,一个输入50构成一个50 by 50矩阵。我是一个初学者程序员,这是我第一次提出堆栈溢出问题,所以请不要太苛刻:) 这是我的代码。

from PIL import Image
import itertools
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
count1 = 0
for n in A:
    x = (int(n[0]) / (inp - 1)) * 2
    y = (int(n[1]) / (inp - 1)) * 2
    if (x ** 2) + (y ** 2) - (2 * x) - (2 * y) <= -1:
        M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1
        count1 += 1
print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2))) ```

标签: pythonnumpy

解决方案


问题出在这一行:M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1 实际上,这一行在某些索引中分配了两次 1 并错过了一些索引,因为您使用的是int(). 用于round()获取最接近的整数。这会有所帮助。更改此行:M[int(x * (inp - 1)/2), int(y * (inp - 1)/2)] = 1到此行:M[round(x * (inp - 1)/2), round(y * (inp - 1)/2)] = 1

您的代码应如下所示:

from PIL import Image
import itertools
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
count1 = 0
for n in A:
    x = (int(n[0]) / (inp - 1)) * 2
    y = (int(n[1]) / (inp - 1)) * 2
    if (x ** 2) + (y ** 2) - (2 * x) - (2 * y) <= -1:
        M[round(x * (inp - 1)/2), round(y * (inp - 1)/2)] = 1
        count1 += 1
print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2)))

我认为这是另一个具有预期输出的解决方案,它是一个简单的解决方案,无需将浮点数转换为整数(对于索引):

import itertools
import numpy as np
np.set_printoptions(threshold=np.inf)
inp = int(input("Input size of matrix"))
dt = np.dtype(np.int8)
M = np.zeros((inp, inp), dtype=dt)
A = (list(itertools.product(range(0, inp), repeat=2)))
# assign the center
cx,cy=int(inp/2), int(inp/2)
# assign the radius
rad=int(inp/2)
count1 = 0
for n in A:
    # calculate distance of a point from the center
    dist = np.sqrt((n[0]-cx)**2+(n[1]-cy)**2)
    # Assign 1 where dist < rad.
    if dist < rad:
        M[n[0], n[1]] = 1
        count1 += 1

print(M)
im = Image.fromarray(M * 255)
im.show()
print("Approximation of pi: " + str(4 * (count1 / inp ** 2)))

推荐阅读