python - 对矩阵应用运算时结果不正确
问题描述
我正在尝试通过将 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))) ```
解决方案
问题出在这一行: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)))
推荐阅读
- react-native - 在使用 EXPO 在 REACT NATIVE 中渲染组件后,如何根据来自选择器的值设置状态?
- java - 带有改造的Android Multipart调用中的动态哈希数组
- java - 如何分析 35-40 GB 左右的大型堆转储
- javascript - 使用 Javascript 比较 3 个相同值的相等性
- python - python 中的 JSON 对象挂钩意外地将我的普通 JSON 更改为嵌套 JSON
- python - Statsmodels 导入问题
- python - 将文件名从列表添加到数据框 - Python
- c - 尝试在 TM4C123 微控制器上的 PB4 上初始化 PWM
- javascript - javascript中的Autodesk 2 Legged Authentication,两个不同的错误
- java - 如何在 Tomcat 中从 IBM mq 异步读取消息