从数组求和值并获得双

时间:2016-07-29 15:41:08

标签: python arrays loops for-loop vector

我试图运行此循环以使n成为十进制数。但是,如果我从向量p调用值,n也会成为向量。

我该如何解决?

羊肉= linspace(400800,NUM = 20)

for k in 1/lamb:
    AR2 = 1.55
    p =  [-0.003396, 0.6518, 66.01, 2435]
    n = 0.00

    for i in range(0, 3): 
        n = n + AR2+ p[i]/k**(10-i)

2 个答案:

答案 0 :(得分:1)

linspace(400,800,num=20)是一个数组。对它执行操作是按元素进行的。例如:

>>> linspace(400,800,num=20)
array([ 400.        ,  421.05263158,  442.10526316,  463.15789474,
    484.21052632,  505.26315789,  526.31578947,  547.36842105,
    568.42105263,  589.47368421,  610.52631579,  631.57894737,
    652.63157895,  673.68421053,  694.73684211,  715.78947368,
    736.84210526,  757.89473684,  778.94736842,  800.        ])

>>> 2 + linspace(400,800,num-20)
array([ 402.        ,  423.05263158,  444.10526316,  465.15789474,
    486.21052632,  507.26315789,  528.31578947,  549.36842105,
    570.42105263,  591.47368421,  612.52631579,  633.57894737,
    654.63157895,  675.68421053,  696.73684211,  717.78947368,
    738.84210526,  759.89473684,  780.94736842,  802.        ])

您不能通过浮点数添加或乘以数组并获得浮点数。问题不在p,而是linspace

答案 1 :(得分:0)

如果我将lambAR2设为数字,那么我就不会看到n成为数组,即

AR2 = 1.55
p =  [-0.003396, 0.6518, 66.01, 2435]
n = 0.00
lamb = 0.97
AR2 = 1

for i in range(0, 3): 
    n = n + AR2+ p[i]*lamb**(10-i)
    print(n)

返回:

 0.9974957076650648 
 4930143116961103
 55.22791346817842

我希望这有帮助!