总体问题:调用时,如何知道从队列对象中得到了什么队列.get()? 如何对其进行排序或标识?你能从队列中获取特定的项目并留下其他项目吗?你知道吗
上下文:
我想学习一点多进程(线程?)使解矩阵方程更有效。你知道吗
为了说明这一点,下面是我在不利用多核的情况下求解矩阵方程Ax=b的工作代码。解是[1,1,1]。你知道吗
def jacobi(A, b, x_k):
N = len(x_k)
x_kp1 = np.copy(x_k)
E_rel = 1
iteration = 0
if (N != A.shape[0] or N != A.shape[1]):
raise ValueError('Matrix/vector dimensions do not match.')
while E_rel > ((10**(-14)) * (N**(1/2))):
for i in range(N):
sum = 0
for j in range(N):
if j != i:
sum = sum + A[i,j] * x_k[j]
x_kp1[i] =(1 / A[i,i]) * (b[i] - sum)
E_rel = 0
for n in range(N):
E_rel = E_rel + abs(x_kp1[n] - x_k[n]) / ((abs(x_kp1[n]) + abs(x_k[n])) / 2)
iteration += 1
# print("relative error for this iteration:", E_rel)
if iteration < 11:
print("iteration ", iteration, ":", x_kp1)
x_k = np.copy(x_kp1)
return x_kp1
if __name__ == '__main__':
A = np.matrix([[12.,7,3],[1,5,1],[2,7,-11]])
b = np.array([22.,7,-2])
x = np.array([1.,2,1])
print("Jacobi Method:")
x_1 = jacobi(A, b, x)
好的,我想按照这个很好的例子来转换代码:https://p16.praetorian.com/blog/multi-core-and-distributed-programming-in-python
所以我得到了一些代码,在相同的迭代次数下运行并收敛到正确的解决方案!那真是太好了,但这能保证什么呢?好像队列.get()只需从最先(或最后?)完成的过程中获取任何结果。正如我所料,当我的代码运行时,我真的非常惊讶
for i in range(N):
x_update[i] = q.get(True)
把向量的元素弄乱。你知道吗
以下是我使用多处理库更新的代码:
import numpy as np
import multiprocessing as mu
np.set_printoptions(precision=15)
def Jacobi_step(index, initial_vector, q):
N = len(initial_vector)
sum = 0
for j in range(N):
if j != i:
sum = sum + A[i, j] * initial_vector[j]
# this result is the updated element at given index of our solution vector.
q.put((1 / A[index, index]) * (b[index] - sum))
if __name__ == '__main__':
A = np.matrix([[12.,7,3],[1,5,1],[2,7,-11]])
b = np.array([22.,7,-2])
x = np.array([1.,2,1])
q = mu.Queue()
N = len(x)
x_update = np.copy(x)
p = []
error = 1
iteration = 0
while error > ((10**(-14)) * (N**(1/2))):
# assign a process to each element in the vector x,
# update one element with a single Jacobi step
for i in range(N):
process = mu.Process(target=Jacobi_step(i, x, q))
p.append(process)
process.start()
# fill in the updated vector with each new element aquired by the last step
for i in range(N):
x_update[i] = q.get(True)
# check for convergence
error = 0
for n in range(N):
error = error + abs(x_update[n] - x[n]) / ((abs(x_update[n]) + abs(x[n])) / 2)
p[i].join()
x = np.copy(x_update)
iteration += 1
print("iteration ", iteration, ":", x)
del p[:]
A
Queue
是先进先出,这意味着按照插入顺序插入的第一个元素是检索到的第一个元素。你知道吗由于您无法控制它,我建议您在队列中插入元组,其中包含值和一些可用于排序/关联原始计算的标识对象。你知道吗
本例将索引与结果放在
Queue
中,这样当.get()
之后您也会得到索引,并使用它来知道这是用于哪个计算:或者类似的。你知道吗
相关问题 更多 >
编程相关推荐