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

Python递归函数实现:寻找满足向量差和阈值的迭代向量

Fixing the Recursive Function for Matrix-Vector Iteration

Let's break down why your recursive function isn't behaving as expected and fix it properly.

The Problem with Your Current Code

Your recursive function has two key issues that prevent it from working correctly:

  • In the else branch, you call diff_sum(M, np.dot(M, v1)) but don't return the result of this recursive call. This means the recursive work gets discarded, and the function just returns the first iteration's values every time.
  • You're unnecessarily recalculating np.dot(M, v1) for the recursive call—v1 is already the result of M*v, so you can just pass v1 directly as the new input vector.

Corrected Recursive Function

Here's the fixed version with clearer logic and proper recursion handling:

import numpy as np

def diff_sum(M, v):
    v_next = np.dot(M, v)
    # Calculate sum of absolute differences between current and next vector
    total_diff = np.sum(np.absolute(v - v_next))
    
    # Check if we've met the threshold
    if total_diff < 0.45:
        return (total_diff, v, v_next)
    # If not, recurse with the next vector (and return the recursive result!)
    else:
        return diff_sum(M, v_next)

Key Improvements

  • Clearer variable names: v_next makes it obvious this is the next iteration of the vector, instead of vague v1.
  • Proper recursion flow: Adding return to the else branch ensures the result from deeper recursive calls is passed back up correctly.
  • Efficient summation: Using np.sum() instead of Python's built-in sum() is more reliable for numpy arrays and performs better with larger data.
  • Avoid redundant calculations: We pass v_next directly to the recursive call instead of recalculating the matrix dot product.

Testing the Function

Let's use your sample data to verify it works:

# Your original matrix and initial vector
M = np.array([[0, 0, 0, 0.5, 0, 0], [1, 0, 0, 0, 0.5, 0], [0, 1, 0, 0, 0.5, 1], [0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0.5, 0, 0]])
M = M.astype(float)
v0 = np.array([1/6, 1/6, 1/6, 1/6, 1/6, 1/6])

# Run the recursive function
diff, vi, vi_plus_1 = diff_sum(M, v0)

print(f"Sum of absolute differences: {diff}")
print(f"Vector v_i: {vi}")
print(f"Vector v_{i+1}: {vi_plus_1}")

This will iterate until it finds the pair of vectors where the sum of absolute differences is below 0.45, just like your manual calculation of v4 and v5.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:07:02