Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the inverse of a linear function

I'm trying to work with linear functions for data conversion (like meters to feet).

I'm trying to find a way to build a lambda function that returns the inverse function and another lambda function that return the composition of those functions

inches_to_meters=lambda x:x*0.0254
inches_to_feets=lambda x:x*(1/12)
miles_to_feets=lambda x:x*5280
composition=lambda x,y,z: lambda x,y: x(y(z))
opposite=lambda x: 1/x
meters_to_inches=opposite(inches_to_meters)
miles_to_inches = composition(feets_to_inches, miles_to_feets)
print(meters_to_inches(10))    

how can I make the opposite function (F^-1(x))?

(For example: y=x/12, then 12*y=x, the opposite is: 12*x=y).

like image 538
arthur Avatar asked Dec 04 '25 14:12

arthur


1 Answers

First, it is better to use the def ... statement rather than lambda to define named functions. Have a look at this SO question and its answers for more details. But if I understand correctly what you want to achieve, it might be better to define the linear function as a class (see below).


The inverse of the linear function:

linear function

is given by:

inverse of linear function

and depends on both the slope a and the intercept b. An important consequence of this is that you need to know both a and b to define its inverse in a functional form.

In python you can achieve this for example if you define a class of linear functions and the inverse as one of its methods:

class f_lin:
    def __init__(self, a, b=0):
        self.a = float(a)
        self.b = b

    def __call__(self, x):
        return self.a * x + self.b

    def inv(self, y):
        return (y - self.b) / self.a

Now you can define:

inches_to_meters = f_lin(0.0254)

and use it like so:

inches_to_meters(10)
Out[38]: 0.254
inches_to_meters.inv(0.254)
Out[39]: 10.0
inches_to_meters.inv(inches_to_meters(10))
Out[40]: 10.0

Alternatively you could also create a new object for the inverse, as the inverse of a linear function is still a linear function:

class f_lin:
    def __init__(self, a, b=0):
        self.a = float(a)
        self.b = b

    def __call__(self, x):
        return self.a * x + self.b

    def get_inverse(self):
        return self.__class__(1/self.a, - self.b/self.a)

Then you can define the inverse function like so:

inches_to_meters = f_lin(0.0254)
meters_to_inches = inches_to_meters.get_inverse()

Now you have both the linear function and its inverse as objects:

inches_to_meters(10)
Out[43]: 0.254
meters_to_inches(0.254)
Out[44]: 10.0
inches_to_meters(meters_to_inches(10))
Out[45]: 10.0

Those are just 2 ways of doing, both not using lambda as requested. However I would advise against doing such things with lambda.

like image 78
jojo Avatar answered Dec 07 '25 15:12

jojo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!