Search code examples
pythonpython-2.7numpytypeerrorpython-cmath

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


I have the following code written in python 2.7. Here I've defined two function, a cosine function and an exponential function and I need to multiply these functions to a float Value, but I am getting this error. I assume we can't multiply a float value to a function in list() format... I would be grateful if someone tell me how can I do this. Thanks in advance. Here is my code :

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)


Solution

  • Sticking to NumPy (and specifically avoiding math/cmath altogether) would just solve the issues you are observing, by completely avoiding non-broadcast-friendly containers / operations:

    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)
    

    (I also fixed some typos here and there, and cleaned/reordered a little bit, although it is not yet fully PEP8-compliant)

    Note that I have replaced the use of np.arange() with an equivalent call to np.linspace(), since as-per its documentation: "When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases."