You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建含三角函数的4x4矩阵并运算?语法错误排查

矩阵创建与乘法运算的语法错误排查与修复

问题背景

尝试使用Python的math和NumPy库创建包含三角函数的4x4矩阵A,以及矩阵B、C,并执行矩阵乘法(A·B)·C时,触发SyntaxError错误,错误指向矩阵A的第二行语法问题。

核心错误点排查

1. 矩阵A的语法与规范问题

  • 中文符号不兼容:使用了中文希腊字母Θ、Φ,Python无法识别,需替换为英文变量名(如theta、phi)
  • 幂运算符号错误:Python中幂运算用**而非^(^是按位异或运算符)
  • 括号不匹配:第二行中cos(2Θ)^2+cos(Φ)sin(2Θ]的右方括号位置错误,且三角函数参数未正确闭合
  • 列表分隔符缺失:矩阵A的第三行与第二行之间、第三行末尾均缺少逗号,导致NumPy无法识别矩阵结构
  • 三角函数调用规范:需确保从math或numpy导入三角函数,推荐使用numpy的三角函数以支持数组运算

2. 矩阵B、C的语法问题

  • 矩阵B、C的定义末尾均缺失闭合的右括号],导致语法不完整

3. 代码执行语法问题

  • 矩阵乘法与打印语句写在同一行,未用分号分隔或换行,不符合Python语法规范

修复后的完整代码

import numpy as np
from math import cos, sin

# 定义角度变量(可自行修改取值)
theta = np.pi / 4
phi = np.pi / 3

# 创建矩阵A
A = np.array([
    [1, 0, 0, 0],
    [0, cos(2*theta)**2 + cos(phi)*sin(2*theta), (1 - cos(phi))*sin(2*theta)*cos(2*theta), -sin(phi)*cos(theta)],
    [0, (1 - cos(phi))*sin(2*theta)*cos(2*theta), sin(2*theta)**2 + cos(phi)*cos(2*theta)**2, sin(phi)*cos(2*theta)],
    [0, sin(phi)*sin(2*theta), -sin(phi)*cos(2*theta), cos(phi)]
])

# 创建矩阵B
B = np.array([
    [0.5, -0.5, 0, 0],
    [-0.5, 0.5, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]
])

# 创建矩阵C
C = np.array([
    [1],
    [1],
    [0],
    [0]
])

# 执行矩阵乘法并打印结果
result = np.dot(np.dot(A, B), C)
print(result)

补充说明

  • 若需对数组批量运算,可直接使用np.cos、np.sin替代math模块的函数,避免类型转换问题
  • NumPy 1.10+版本支持@运算符替代np.dot,矩阵乘法可简化为result = A @ B @ C

内容的提问来源于stack exchange,提问作者David hwang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:26:59