不支持的操作数类型

不支持的操作数类型

本文介绍了TypeError:Python 3.6.8中+:不支持的操作数类型:"float"和"list"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断得到TypeError: unsupported operand type(s) for +: 'float' and 'list'.

我是python编程的新手,正在尝试将Matlab代码转换为Python.下面是尝试过的python代码.

I am new to python programming and am trying to convert Matlab code into Python. Below is the tried python code.

import math
import cmath
import numpy as np
import random

Tp = .1e-6
Xc = 2.e3
c = 3e8
B0 = 100e6
X0 = 50
w0 = 2 * cmath.pi * B0
fc = 1e9
wc = 2*cmath.pi * fc
alpha = w0 / Tp
wcm = wc - alpha * Tp
Ts = (2 * (Xc - X0)) / c
Tf = (2 * (Xc - X0)) / c + Tp
dt = cmath.pi / (2 * alpha * Tp)
n = 2 * math.ceil((0.5 * (Tf - Ts)) / dt)
t = Ts + np.arange(0, n*dt, dt)

dw = 2*cmath.pi / (n * dt)
w = wc + dw * np.arange(-n/2,n/2)
xn = [0, 35, 36.5, -25]
fn = [1, 0.8, 1, 0.8]

ntarget = 4

# SIMULATION

s = np.zeros((1,n))
na = 8
ar = random.uniform(1,na)
ter = 2 * cmath.pi * random.uniform(1,na)

for i in np.arange(ntarget):
td = t - (2 * (Xc + xn[i]) / c)
pha = wcm * td + alpha * np.power(td, 2)
for j in np.arange(na):
    pha = pha + ar[j] * math.cos((w[n/2 + 1 + [j]] - wc) * td + ter[j])

print('pha :', pha)

错误消息:

Error at
    pha = pha + ar[j] * math.cos((w[n/2 + 1 + [j]] - wc) * td + ter[j])

TypeError: unsupported operand type(s) for +: 'float' and 'list'

pha的预期输出是一个介于1和286之间的数字的数组/列表,即[-940.7325, -729.3720,......,6.6187*e4,6.6449*e4]

Expected output of pha is an array/list of numbers between 1 and 286, i.e [-940.7325, -729.3720,......,6.6187*e4,6.6449*e4]

我非常感谢我所能提供的所有帮助.非常感谢.

I appreciate all the help I can get. Thanks a lot.

推荐答案

存在多个问题.在表达式math.cos((w[n/2 + 1 + [j]] - wc)中,通过执行[j]将整数j放入单个元素列表中.因此[j] + any_number不再起作用.

There are multiple problems. In the expression math.cos((w[n/2 + 1 + [j]] - wc) you are putting the integer j in a single element list by doing [j]. Hence [j] + any_number does not work anymore.

此外,您正在索引arter,但这只是一个数字(请参见 random.uniform ).如果要使用特定大小的数组/向量,可以使用 np.random.uniform size参数.

Furthermore, you are indexing ar and ter, but these are one number (see random.uniform). If you want an array/vector of a specific size, you can use np.random.uniform with the size argument.

以下内容应该可以使用,但是在每次循环迭代中使用相同的随机值arter:

The following should work, but uses the same random values ar and ter on each loop iteration:

s = np.zeros((1,n))
na = 8
ar = random.uniform(1,na)
ter = 2 * cmath.pi * random.uniform(1,na)

for i in np.arange(ntarget):
    td = t - (2 * (Xc + xn[i]) / c)
    pha = wcm * td + alpha * np.power(td, 2)
    for j in np.arange(na):
        pha = pha + ar * math.cos((w[n/2 + 1 + j] - wc) * td + ter)
        print('pha :', pha)

这篇关于TypeError:Python 3.6.8中+:不支持的操作数类型:"float"和"list"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:10