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

numpy dot点积cross叉乘返回值异常 向量旋转函数Bug排查

向量绕指定轴旋转函数计算结果异常排查

问题背景

我正在编写实现向量绕指定轴旋转指定角度的函数,运行时出现计算结果异常的问题,以下是用于故障排查的测试代码:

import numpy as np

def unit_vector(vec):
    vec = np.array(vec, float)
    unit_vec = []
    for i in range(len(vec)):
        unit_vec.append(vec[i]/np.linalg.norm(vec))
    return np.array(unit_vec, float)


def rotation(vector,axis, angle):
    vector = np.array(vector, float)
    axis = np.array(vector, float)
    first  = vector * np.cos(angle)
    second = np.cross(vector, unit_vector(axis))
    third = unit_vector(axis)
    fourth = np.dot(vector, unit_vector(axis))
    fifth = 1 - np.cos(angle)
    print("first : {0} \nSecond : {1} \nThird : {2}\nFourth : {3}\nFifth : {4}\n ".format(list(first), list(second), list(third),fourth, fifth))

rotation([0,1,0],[0,0,1],np.pi/2)

程序运行输出如下:

first : [0.0, 6.123233995736766e-17, 0.0]
Second : [0.0, 0.0, 0.0]
Third : [0.0, 1.0, 0.0]
Fourth : 1.0
Fifth : 0.9999999999999999

异常点说明

  • 输出中second计算结果为[0.0, 0.0, 0.0]、fourth计算结果为1.0
  • 按旋转计算逻辑,只有输入向量和旋转轴方向完全一致时才会出现这类结果,但本次测试传入的向量是[0,1,0]、旋转轴是[0,0,1],二者互相垂直,方向完全不同
  • 单独在函数外部计算对应变量时结果正常,仅函数内计算出错

故障根因

是非常低级的笔误导致的:
rotation函数里做参数类型转换时,你写的是axis = np.array(vector, float),这行代码根本没有调用传入的axis参数,直接把已经转成numpy数组的输入向量vector赋值给了axis变量,等于你传进来的旋转轴[0,0,1]直接被覆盖成了和输入向量完全相同的[0,1,0],后续所有和旋转轴相关的计算,实际都是拿输入向量本身当轴算的:

  • 两个完全同向的向量叉乘结果必然是零向量,对应second的输出[0,0,0]
  • 向量和自身单位向量的点积结果必然为1,对应fourth的输出1.0

修复方案

把笔误的那行参数转换代码改成正确的传入axis参数即可:

axis = np.array(axis, float)

修改后重新运行,就能得到符合预期的计算结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:15:45