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

如何在Java中实现高斯消元算法中的argmax函数

Java实现argmax函数

此处的argmax逻辑为:在[h, m]行范围内,查找第k列元素绝对值最大的行索引。

注意:伪代码使用1作为索引起点,以下实现适配Java数组默认的0索引规则,若你的矩阵实现采用1索引,调整遍历边界即可。

// 入参说明:matrix为输入的二维矩阵,startRow对应伪代码的h,endRow对应伪代码的m,col对应伪代码的k
public static int getArgMax(double[][] matrix, int startRow, int endRow, int col) {
    int maxIndex = startRow;
    double maxAbsValue = Math.abs(matrix[startRow][col]);
    // 遍历范围内的所有行
    for (int i = startRow + 1; i <= endRow; i++) {
        double currentAbs = Math.abs(matrix[i][col]);
        if (currentAbs > maxAbsValue) {
            maxAbsValue = currentAbs;
            maxIndex = i;
        }
    }
    return maxIndex;
}

调用注意事项

  • 浮点数计算存在精度误差,不要直接用== 0判断主元是否为0,建议判断元素绝对值是否小于极小阈值,示例:
int pivotRow = getArgMax(matrix, h, m, k);
if (Math.abs(matrix[pivotRow][k]) < 1e-9) {
    // 无有效主元,跳过当前列
    k++;
} else {
    // 交换行,执行后续消元逻辑
    swapRows(matrix, h, pivotRow);
    // 消元逻辑省略
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:27:02