1

I am wondering if there is any way of adding to lambda functions at the function level.

import numpy as np

f = lambda x: np.sin(5*x)+3
g = lambda x: np.cos(3*x)**2+1

x = np.linspace(-3.14,3.14,1000)
h = f+g  % is there any way to create this ?
h_of_x = h(x)

This would be very helpful.

7
  • 4
    You mean like h = lambda x: f(x) + h(x)? Commented May 5, 2015 at 18:38
  • 4
    Or you mean h = lambda x: f(g(x))? Commented May 5, 2015 at 18:39
  • Sure would be cute if function addition could be defined by providing them with an __add__ attribute: a.__add__ = lambda self, b: return lambda *x: self(*x) + b(*x). But python doesn't seem to care if functions have an __add__ method :-) Commented May 5, 2015 at 18:49
  • 1
    Ok, it doesn't work OOTB, but as @shx2's answer shows, there's a library for it! Neat. Commented May 5, 2015 at 18:52
  • @alexis, Yes but I like to refrain from mixing sympy with numpy as it gives weird error messages when you manipulate functions (32 dimensions limit) Commented May 5, 2015 at 18:53

3 Answers 3

4

If you're looking for symbolic mathematics, use sympy.

from sympy import *
x = symbols("x")
f = sin(5*x)+3
g = cos(3*x)**2+1
h = f + g
Sign up to request clarification or add additional context in comments.

Comments

3

May be this

h = lambda x: f(x)+g(x)

Comments

2

You can create a function plus that takes two functions as input and return their sum:

def plus(f, g):
    def h(x):
        return f(x) + g(x)
    return h

h = plus(lambda x: x * x, lambda x: x ** 3)

Example:

>>> h(2)
12

Defining plus can have advantages, like:

>>> f = lambda x: x * 2
>>> h = reduce(plus, [f, f, f, f]) # or h = reduce(plus, [f] * 4)
>>> h(2)
16

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.