Create a math function with the 'dummy' variable, which will be evaluated later.

I am trying to create a function in python that will add a bunch of math terms together that include some arbitrary variable name that will be evaluated after everything is built. For example,

def transform(terms, xterm):
    function=.5
    step=terms
    odd=1
    while step>0:
        function+=(2/odd*np.pi)*np.sin(odd*np.pi*xterm)
        odd+=2
        step-=1
    return function

test=transform(10,somexvariable) 
print test   

This is the Fourier series for the specific function that I had to do in the mechanics class.

Basically, I want the number of terms (e.g. 5) to create a variable that looks like this:

function = .5 + (2/odd*np.pi)*np.sin(odd*np.pi*xvariable) +....... 

due to the fact that many terms i want, where the variable "odd" is the only number that changes.

The key and difficulty for this problem is to insert some dummy variable that I called "xvariable" so that I can create an array like this later:

x2 = np.arange(0,10,.05)
y = transform(2,x2)

x, , "transform".

, , , , .

. !

+4
1

, functools.partial. .

from functools import partial

def sum_powers(x, terms):
    result = 0
    for term in terms:
        result += term ** x
    return result

sum_squares = partial(sum_powers, x=2)
sum_squares(terms=[1, 2, 3])
# 14

sum_cubes = partial(sum_powers, x=3)
sum_cubes(terms=[1, 2, 3])
# 36
+2

Source: https://habr.com/ru/post/1627377/


All Articles