0

I am absolutly new in Python, and I have difficulties using numpy in following way.

My goal is to make a function object which computes f(input) - g(input) I have the following class:

class MyFunc:
    def __init__(self, f: callable, g: callable):
        self.f: callable = f
        self.g: callable = g

    def f(self, x: float):
        fresult: float = self.f(x)
        gresult: float = self.g(x)
        result: float = fresult - gresult
        # return self.f(x) - self.g(x)
        return result

I am passing numpy functions to object of this class. Like this:

import numpy as np
f1 = np.poly1d([0.1381, 0.01081, 0.09903, - 0.9153, - 0.4032])
f2 = np.poly1d([-0.6902, - 0.1294, - 0.1718, - 1.07, 0.1351])

foo = MyFunc(f1, f2)

The problem is when I am passing an input to foo.f, it computes just f1(input) not f1(input) - f2(input)

What I have done wrong?

How should I write this correctly?

Here is an example of getting unexpected output:

f1 = np.poly1d([0.1381, 0.01081, 0.09903, - 0.9153, - 0.4032])
f2 = np.poly1d([-0.6902, - 0.1294, - 0.1718, - 1.07, 0.1351])

foo = MyFunc(f1, f2)
value: float = -0.41757
r1 = f1(value) # -0.000319....
r2 = f2(value) # 0.54038....
# I expect fresult = result
result = r1 - r2 # -0.5407....
fresult = foo.f(value) # -0.000319....

1 Answers1

0

Define your class as:

class MyFunc:
    def __init__(self, f: callable, g: callable):
        self.f: callable = f
        self.g: callable = g

    def fn(self, x: float):
        fresult: float = self.f(x)
        gresult: float = self.g(x)
        result: float = fresult - gresult
        return result

Note that I changed your f function to fn, in order to keep it as a separate object, because you have already f as one of attributes, set in the constructor.

Then call it as:

fresult = foo.fn(value)

(with the changed function name).

But maybe a simpler approach, without any custom class, is to compute:

foo = np.polysub(f1, f2)
result = foo(value)

Or even shorter:

result = np.polysub(f1, f2)(value)
Valdi_Bo
  • 30,023
  • 4
  • 23
  • 41