bananagurlz bananagurlz - 1 year ago 72
Python Question

Creating a python function to output a periodic function

I am trying to create a python function that makes the output a periodic function. But, I do not know how to code a variable, say X, to work as the output. I know to use Sympy for something with an output of x**2, but for some reason I cannot use the variable the same way. When I try to use sympy to get some output function that would be, for a random example, cos(4x), the error explanation I get from python is "'Symbol' object has no attribute 'cos'". How can I write a function that could give me the output cos(4x) in python where the output is cos(4x) the function, not cos(4x) evaluated at some predetermined x)?

Answer Source

functions are objects. You can define a function inside a function and then return that newly defined function. These are referred to as closures

import sympy

def expansion(coef1, coef2):
    def exp(x):
        return sympy.cos(coef1*x) + sympy.cos(coef2*x)
    return exp

c1 = 1
c2 = 2

my_exp = expansion(c1, c2)

x = sympy.symbols("x")


cos(x) + cos(2*x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download