简体   繁体   中英

Python: Finite sum with variable range “TypeError: only integer scalar arrays can be converted to a scalar index”

Aim: plot V vs. MF

方程

import numpy as np

V = np.arange(3,46, step = 6)
A = 3

# 'n' is a sequence of odd numbers (i.e. 1,3,5,7, ...)
n = V/A

mm = (n+1)/2
MF = sum((np.power(-1, m)) * np.exp(m * m * (V/n)) for m in range(1,mm))

I want m to form a sequence of 1, 2, 3, ... (n+1)/2 .

The problem I'm having is with the final line range(1,mm) which returns

TypeError: only integer scalar arrays can be converted to a scalar index

Seems to me the problem is that m cannot be variable for different numbers in the same sequence. Is there a way around this?

mm variable is a numpy array containing the sequence of 1, 2, 3 ... so range(1, mm) part doesn't make sense since range expects its arguments to be integers. If you want to iterate on mm , you can just

MF = sum((np.power(-1, m)) * np.exp(m * m * (V/n)) for m in mm)

Note : This is probably not what you want because V is a np.array, it makes resulting expression an array.

Since you are using numpy, you do not need to iterate on mm yourself. You can use mm directly:

MF = np.sum((-1) ** mm * np.exp(mm ** 2 * A))
>>> 2.4240441494100796e+83

import numpy as np

V = np.arange(3,46, step = 6)

A = 3

'n' is a sequence of odd numbers (ie 1,3,5,7, ...)

n = V/A

'm' is the upper limit of summation; indices of summation are every integer between 1 to m.

m = (n+1)/2

'y' represents the element to be summed

y = np.power(-1, m) * np.exp((m**2)*A)

MF = np.add.accumulate(y)

print(n)

print(MF)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM