این برنامه پایتون دو بردار یکبعدی a و b را دریافت کرده و حاصل ضرب بیرونی آنها را در ماتریس c ذخیره میکند.
ضرب بیرونی بهصورت c[i][j] = a[i] × b[j] تعریف میشود.
def outer_product(a: list[float], b: list[float]) -> list[list[float]]:
rows = len(a)
cols = len(b)
c = [[a[i] * b[j] for j in range(cols)] for i in range(rows)]
return c
def print_matrix(matrix: list[list[float]]):
print("ماتریس حاصل ضرب بیرونی:")
for row in matrix:
print(" ".join(f"{val:.1f}" for val in row))
# دادههای نمونه
a = [2.2, 0.0, 4.4]
b = [2.0, 1.0, 3.0, 2.0]
# محاسبه ضرب بیرونی
c = outer_product(a, b)
# چاپ نتیجه
print_matrix(c)
ماتریس حاصل ضرب بیرونی:
4.4 2.2 6.6 4.4
0.0 0.0 0.0 0.0
8.8 4.4 13.2 8.8