Math function, unassigned variables?

I am looking for a way to add some math functions before assigning numeric values ​​to variables in equations. I do it this way because I need to optimize my code and I want to assign different values ​​to the variables every time. An example of what I am trying to do:

  • f(x, y) = x + 2y

  • g(x, y) = 3x - y

  • adds f(x, y) + g(x, y)

    to get h(x, y)

    , sof(x, y) + g(x, y) = h(x, y) = 4x + y

  • Now that I have h(x, y)

    , I need multiple values ​​fromh(x, y)

x = 4; y = 3, h(x, y) = 19
x = 1, y = 0, h(x, y) = 4

      

and etc.

Is it possible? I tried to create them as strings, add strings and then remove the quotes to estimate the sum, but that didn't work. I am trying to make my method this way because I want to optimize my code. It helps a lot if I can create my last function before evaluating it (in which case it will h(x, y)

).

EDIT: I am doing (e ** (x + y)) additions, so linear solutions using matrices don't work: /

+2


source to share


3 answers


SymPy can do this:

import sympy as sym

x, y = sym.symbols('xy')
f = x + 2*y
g = 3*x - y
h = f + g

      

This shows that SymPy has simplified the expression:



print(h)
# y + 4*x

      

And that shows how you can evaluate h

both a function x

and y

:

print(h.subs(dict(x=4, y=3)))
# 19
print(h.subs(dict(x=1, y=0)))
# 4

      

+7


source


If all functions are linear combinations of variables as shown in the examples, there is no need for the parser or sympy solution suggested by @unutbu (which seems to be the correct answer for complex functions).

For linear combinations, I would use arrays numpy

to hold the coefficients of the variables as shown below:



import numpy as np
f = np.array([1,2])
g = np.array([3,-1])
h = f + g
x = np.array([4,3])
sum(h*x)

      

... which gives an answer 19

as in your example.

+2


source


You can use lambda functions as well.

f=lambda x,y:x+2*y
g=lambda x,y:3*x-y
h=lambda x,y:f(x,y)+g(x,y)

      

and rate h(x,y)

0


source







All Articles