numpy cumsum()函数失效?求正确累加求和实现方法
Hey there! Let's figure out why you're seeing this discrepancy and how to fix it.
First, let's break down the core issue: You're expecting a cumulative sum result of [4, 10, 22], but instead getting back what looks like your original array [4, 6, 12]. Here's what might be going on, plus alternative methods to get the result you want.
Why isn't cumsum() working as expected?
Chances are, either you're not using cumsum() correctly, or your input array isn't what you think it is:
- If your input array is
[4, 6, 12], a propercumsum()should return[4, 4+6=10, 10+12=22]. If you're seeing the original array, you might be printing the input instead of thecumsum()result. - If your input array is actually
[4, 2, 6], thencumsum()would correctly return[4, 6, 12]—double-check your source data!
Alternative Methods to Get Your Desired Cumulative Sum
If for some reason cumsum() isn't working for you (or you're in an environment without it), here are reliable ways to implement the cumulative sum you need:
1. Manual Loop (Works in Any Language)
This is the most straightforward approach—track a running total and build your result list step by step:
# Example in Python input_arr = [4, 6, 12] cumulative_sum = [] running_total = 0 for num in input_arr: running_total += num cumulative_sum.append(running_total) print(cumulative_sum) # Output: [4, 10, 22]
2. Use Built-in Tools (Python-Specific)
If you're using Python, the itertools module has a ready-made accumulate() function that does exactly this:
from itertools import accumulate input_arr = [4, 6, 12] cumulative_sum = list(accumulate(input_arr)) print(cumulative_sum) # Output: [4, 10, 22]
3. Fix Your cumsum() Usage
If you want to stick with cumsum(), make sure you're assigning its result to a variable and using it correctly. For example, with NumPy:
import numpy as np input_arr = np.array([4, 6, 12]) cumulative_sum = input_arr.cumsum() print(cumulative_sum) # Output: [ 4 10 22 ]
Double-check that you're not accidentally printing the original input array instead of the cumulative sum result—this is a super common mistake!
内容的提问来源于stack exchange,提问作者Nick X Tsui

