Diogo
Diogo

Reputation: 64

Sum of Functions in Python

I have a function f(x,a) where 'x' is a variable and 'a' is a parameter. I want creat a function F(x) that is a sum of f(x,a) for a range of parameter 'a', for instance: F(x) = f(x,a1) + f(x,a2) + f(x,a3) + ... + f(x,aN) but how I have a large range for 'a' (a=[a1,a2,a3,...,aN]) I want to write a program for this but I don't now how. For instance:

import numpy as np
# Black-Body radiation equation: 'x' is related to frequency and 'a' is related to temperature 
def f(x,a):
    return x**3/(np.exp(a*x) - 1)

# range for parameter a:
a = [1000,2000,3000,4000,5000,6000]

# Superposition of spectrum
def F(x):
    return f(x,a[0]) + f(x,a[1]) + f(x,a[2]) + f(x,a[3]) + f(x,a[4]) + f(x,a[5])

The last line for function F(x) isn't very smart, so I tried make a loop in the above sum with sum() function

def F(x):
spectrum = []
    for i in a:
        spectrum = sum(f(x,i))
    return spectrum

But as I don't have much experience with Python this doesn't work and I got the error:

import matplotlib.pyplot as plt
x = np.linspace(0,100,500)
plt.plot(x,F(x))
plt.show()
# ValueError: x and y must have same first dimension, but have shapes (500,) and (1,)

Does anyone know how to do this? thank you very much

Upvotes: 1

Views: 991

Answers (1)

SPH
SPH

Reputation: 498

From what i understand, this should do the job:

def F(x):
    return sum(f(x, _a) for _a in a)

The thing I do in the sum() function is called list comprehension, feel free to look this Python feature if you are interested by Python coding: it is very powerful.

Upvotes: 2

Related Questions