2

I am looking for a way to add together multiple mathematical functions before assigning the numerical values for the variables in the equations.
I am doing it this way because I need to optimize my code, and I want to assign different values to the variables each time. An example of what I am trying to do:

  1. f(x, y) = x + 2y

  2. g(x, y) = 3x - y

  3. adds f(x, y) + g(x, y) to get h(x, y), so f(x, y) + g(x, y) = h(x, y) = 4x + y

  4. Now that I have h(x, y), I need multiple values from h(x, y)

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

etc.

Is this possible? I was trying to create them as strings, add the strings, then remove the quotes to evaluate the sum but this did not work. I am trying to do my method this way because I want to optimize my code. It would help very much if I am able to create my final function before evaluating it (it would be h(x, y) in this case).

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

Paul Terwilliger
  • 1,596
  • 1
  • 20
  • 45
  • You are basically looking for a parser. Check out [PLY](http://www.dabeaz.com/ply/) - python's version of lex and yacc – Sudipta Chatterjee Feb 03 '13 at 01:36
  • Even with e**(x+y), a matrix solution might work for cases where the exponential can be transformed appropriately. e.g. e**(x+y) == e**x * e**y so, if each of the terms is a vector, the two vectors could be multiplied together, giving a much faster solution than I expect `sympy` could give. For the general case where there isn't an appropriate transformation, though, @unutbu's solution is very attractive. – Simon Feb 03 '13 at 07:58
  • How would I use matrices to do this? I'm working with equations that might look like... e^ipi(4x - 2y) + e^ipi(10x + 3y) + e^ipi(x + 24y)... – Paul Terwilliger Feb 03 '13 at 17:23

3 Answers3

8

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 this shows how you can evaluate h as a function of x and y:

print(h.subs(dict(x=4, y=3)))
# 19
print(h.subs(dict(x=1, y=0)))
# 4
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
2

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

For linear combinations, I'd use numpy arrays to contain the coefficients of the variables, as follows:

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 the answer 19, as in your example.

Simon
  • 10,679
  • 1
  • 30
  • 44
1

You can also use lambda functions.

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 evaluate h(x,y)

Erik
  • 155
  • 2
  • 10