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
elsebranch, you calldiff_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—v1is already the result ofM*v, so you can just passv1directly 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_nextmakes it obvious this is the next iteration of the vector, instead of vaguev1. - Proper recursion flow: Adding
returnto theelsebranch ensures the result from deeper recursive calls is passed back up correctly. - Efficient summation: Using
np.sum()instead of Python's built-insum()is more reliable for numpy arrays and performs better with larger data. - Avoid redundant calculations: We pass
v_nextdirectly 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
相关产品推荐
相关产品推荐

