繁体   English   中英

Python:可变范围内的有限和“ TypeError:仅整数标量数组可以转换为标量索引”

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

目的:绘制V与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))

我希望m形成一个1, 2, 3, ... (n+1)/2的序列。

我遇到的问题是返回的最终行range(1,mm)

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

在我看来,问题在于,对于相同序列中的不同数字, m不能是变量。 有没有解决的办法?

mm变量是一个numpy数组,包含1, 2, 3 ...的序列,因此range(1, mm)部分没有意义,因为range期望其参数为整数。 如果要迭代mm ,则可以

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

注意:这可能不是您想要的,因为V是np.array,它使结果表达式成为数组。

由于您使用的是numpy,因此您无需自己遍历mm 您可以直接使用mm

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'是一个奇数序列(即1,3,5,7,...)

n = V/A

“ m”是求和的上限; 总和的索引是1到m之间的每个整数。

m = (n+1)/2

“ y”表示要求和的元素

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

MF = np.add.accumulate(y)

print(n)

print(MF)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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