将浮点数乘以 Python 中的函数,并且无法将序列乘以 'float' 类型的非整数

Multiplying a float Number to a Function in Python and getting can't multiply sequence by non-int of type 'float'

我在python 2.7 中编写了以下代码。 这里我定义了两个函数,一个余弦函数和一个指数函数 我需要将这些函数乘以浮点值,但出现此错误。 我假设我们不能将浮点值乘以 list() 格式的函数... 如果有人告诉我该怎么做,我将不胜感激。 提前致谢。 这是我的代码:

import numpy as np
import math
import cmath

delta  = 2.0*math.pi*1.46*((1.0/1530)-(1.0/1550))

#defining main func
def apFunc(x):
    return np.exp(-4*math.log(2)*((x-(5/2))/5)**2)*(1+math.cos((2*math.pi/0.001)*x))
Domain = list(np.arange(0,5,0.001))
APF    = map(apFunc,Domain)

#defining modulation function 
def modFunc(x):
    return (1+math.cos((2*math.pi/0.001)*x))
d      = list(np.arange(0,5,0.001))
mod    = map(modFunc,d)

#making sig and kaa functions
sgima  = (2*math.pi/1530)*APF
sig    = sigma + delta
kaa    = (math.pi/l1530)*mod
gamma  = math.sqrt(sig**2 + kaa**2)

哇哦,里面有很多。

友情提示 - 提供堆栈跟踪可以更轻松地为您提供帮助,同时将代码减少到仅包含重要部分。

针对你的实际问题-

mod 是 map(modFunc,d)

map returns 列表所以 mod = [..., ...] 然后 kaa = (pi) * mod

(pi) * [..., ...]

这没有多大意义。您可能也想要那里的地图?

坚持使用 NumPy(特别是完全避免 math/cmath)将通过完全避免非广播友好的容器/操作来解决您观察到的问题:

import numpy as np


delta = 2.0 * np.pi * 1.46 * ((1.0 / 1530) - (1.0 / 1550))


def apFunc(x):
    return np.exp(-4 * np.log(2) * ((x - (5 / 2)) / 5) ** 2) * (
        1 + np.cos((2 * np.pi / 0.001) * x)
    )


def modFunc(x):
    return 1 + np.cos((2 * np.pi / 0.001) * x)


d = np.linspace(0.0, 5.0, 5000)
APF = apFunc(d)
mod = modFunc(d)

# making sig and kaa functions
sigma = (2 * np.pi / 1530) * APF
sig = sigma + delta
kaa = (np.pi / 1530) * mod
gamma = np.sqrt(sig ** 2 + kaa ** 2)

(我还修正了一些拼写错误,cleaned/reordered 一点点,虽然它还没有完全符合 PEP8

请注意,我已将 np.arange() 的使用替换为对 np.linspace() 的等效调用,因为根据其文档:“使用非整数步骤时,比如0.1,结果往往会不一致,这种情况最好用numpy.linspace。"