0

I have an array of data-points, for example:

[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

and I need to perform the following sum on the values:

enter image description here

However, the problem is that I need to perform this sum on each value > i. For example, using the last 3 values in the set the sum would be:

enter image description here

and so on up to 10. If i run something like:

import numpy as np

x = np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
alpha = 1/np.log(2) 

for i in x:
    y = sum(x**(alpha)*np.log(x))
print (y)

It returns a single value of y = 247.7827060452275, whereas I need an array of values. I think I need to reverse the order of the data to achieve what I want but I'm having trouble visualising the problem (hope I explained it properly) as a whole so any suggestions would be much appreciated.

5
  • 3
    Just get rid of the for loop and the sum. It's simply y = x**(alpha)*np.log(x) or perhaps y = x**(alpha)*np.log(x).cumsum() Commented May 25, 2020 at 12:14
  • Thanks, I thought I had already tried that but it seems I decided to just overcomplicate things! Commented May 25, 2020 at 12:19
  • Why do you need/expect an array of output values? You are summing over x, a one-dimensional array, and thus you end up with a scalar. Is the formula written incorrectly? Should i=1 be a variable instead, like i=j, and j runs from 1 to 10? That is what I gather from your example code. Commented May 25, 2020 at 12:29
  • @roganjosh - why not make an answer of your comment? Commented May 25, 2020 at 12:57
  • @AmitaiIrron I'm not convinced that it adds anything to the SO repository of knowledge since it fixes a single case that isn't expressed clearly in a title. Feel free to take the approach in my comment and post as an answer, though. Commented May 25, 2020 at 13:01

1 Answer 1

1

The following computes all the partial sums of the grand sum in your formula

import numpy as np

# Generate numpy array [1, 10]
x = np.arange(1, 11)
alpha = 1 / np.log(2)
# Compute parts of the sum
parts = x ** alpha * np.log(x)
# Compute all partial sums
part_sums = np.cumsum(parts)
print(part_sums)

You really do not any explicit loop, or a non-numpy operation (like sum()) here. numpy takes care of all your needs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.